Android Network Programming (5) Use of Volley Framework

1 Introduction

We usually develop network requests in Android program trials, and Android itself also provides HttpURLConnection and HttpClient to perform network request communication. But HttpURLConnection and HttpClient will inevitably be a bit complicated to use. Volley network communication framework was introduced at the 2013 Google I / O conference. The characteristic of Volley is that it is simple to use and is suitable for network request operations with small data volume and frequent communication and large volume.

2 Download

Volly's official website address is: https://developer.android.com/training/volley/index.html , the source code is: https://github.com/google/volley . After downloading the source code, we can compile it into a jar package or aar file. Use Android Studio to open the project and directly click "Build"-"Make Project" in the menu bar to generate the aar file directly in \ build \ outputs \ aar \. There are no resources in the aar file, only one classes.jar and two AndroidManifest.xml. So you can choose to import the aar file directly from your own project or extract the jar file and import it for use.

If you do not want to download the source code and compile, you can directly rely on Gradle:

dependencies {
    ...
    compile 'com.android.volley:volley:1.1.1'
}

3 Use

The use of Volley is very simple, in fact, it is four steps:

1. Add access network permission in AndroidManifest.xml <uses-permissionandroid: name = "android.permission.INTERNET" />

2. Create a RequestQueue object

3. Create a Request object

4. Add the Request object to the RequestQueue object

note:

When we introduced Volley earlier, we mentioned that Volley is suitable for high-concurrency network request operations, so we do not have to create multiple RequestQueue objects to request network operations, because this is a waste of resources. In general, we use a singleton to use a RequestQueue in the entire project.

3.1 Use of StringRequest

StringRequest inherits from Request. Step 3 of the four steps we just mentioned creates a Request object. Now use StringRequest to implement a URL request and then return the access result:

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://www.xxx.com",
        new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                // 请求成功
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                // 请求失败
            }
        });
requestQueue.add(stringRequest);

In the example, first a RequestQueue object is created through the Volley.newRequestQueue method; then a request object StringRequest object is created. The StringRequest class constructor receives four parameters, namely the request type (GET or POST), request URL, request success callback and Request failure callback; finally, add this StringRequest object to the RequestQueue queue and you're done.

I do n’t know if the readers have found that the StringRequest class has a big flaw, that is, it does not support incoming parameters, but we know that StringRequest inherits from Request, and from the source code, we can see that the Request class has a method getParams, this method returns The value is the parameter requested by the final request. So we slightly modified the above code:

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, "http://www.xxx.com",
        new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                // 请求成功
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                // 请求失败
            }
        }) {
    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> map = new HashMap();
        map.put("params1", "value1");
        map.put("params2", "value2");
        // ...
        return map;
    }
};
requestQueue.add(stringRequest);

In this way, it is possible to perfectly support network requests with parameters, because we usually bring parameters in POST requests. If it is not supported, it is really wasteful.

3.2 Use of JsonRequest

JsonRequest is also inherited from Request. The use of JsonRequest is similar to that of StringRequest, except that the type of the callback is a Json object, not a String string. JsonRequest itself is an abstract class, and its implementation is completed by JsonObjectRequest and JsonArrayRequest. It should be possible to guess from the name that one of their requests returns the received Json data and the other returns the received Json array. Let's take a look at their implementation:

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

// 带参数的JsonObjectRequest请求
Map<String, String> params = new HashMap();
params.put("params1", "value1");
params.put("params2", "value2");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, "http://www.xxx.com", new JSONObject(params),
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                // 请求成功
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // 请求失败
            }
        });
requestQueue.add(jsonObjectRequest);

// 不带参数的JsonArrayRequest请求
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, "http://www.xxx.com", null,
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray jsonArray) {
                // 请求成功
            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                // 请求失败
            }
        });
requestQueue.add(jsonArrayRequest);

3.3 Use of ImageRequest

For the same reason, ImageRequest also inherits from Request, let's take a look at its use example directly:

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
ImageRequest imageRequest = new ImageRequest(
        "http://xxx.png",                        // 请求图片地址
        new Response.Listener<Bitmap>() {      // 请求成功回调
            @Override
            public void onResponse(Bitmap bitmap) {
                //imageView.setImageBitmap(bitmap);
            }
        },
        0,                                        // 图片最大宽度,如果比原图小,则会进行压缩处理,0表示获取原图大小不会进行压缩
        0,                                        // 图片最大高度,如果比原图小,则会进行压缩处理,0表示获取原图大小不会进行压缩
        ImageView.ScaleType.CENTER_INSIDE,   // 指定图片进行压缩的缩放类型,默认CENTER_INSIDE,表示保持宽高比例缩小图片
        Bitmap.Config.ARGB_8888,              // 指定图片的颜色属性,ARGB_8888可以展示最好的颜色属性,每个图片像素占据4个字节的大小,而RGB_565则表示每个图片像素占据2个字节大小
        new Response.ErrorListener() {       // 请求失败回调
            @Override
            public void onErrorResponse(VolleyError error) {
                //imageView.setImageResource(R.drawable.default_image);
            }
        });
requestQueue.add(imageRequest);

It can be seen that the parameters of ImageRequest are slightly different from the previous StringRequest and JsonRequest. For parameter descriptions, please see the comments in the code above.

3.4 Use of ImageLoader

ImageLoader does not inherit the Request class like the previous XXXRequest. It uses ImageRequest to implement it internally. It can be said that it is an upgrade based on ImageRequest. It can cache the network request pictures to avoid some repeated network requests , So it's more efficient than ImageRequest. Let's take a look at the example below:

RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView, R.drawable.default_image, R.drawable.failed_image);
ImageLoader imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() {
    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        // TODO 在这里要将bitmap添加入缓存
    }

    @Override
    public Bitmap getBitmap(String url) {
        // TODO 在这里要做返回缓存中的图片
        return null;
    }
});
imageLoader.get("http://xxx.png", listener, 100, 100);

Description:

1. The first step is to define a RequestQueue object;

2. Create an ImageListener object. The creation method receives three parameters. The first parameter specifies the ImageView control used to display the image. The second parameter specifies the image displayed during the loading of the image. The third parameter specifies the failure to load the image. The picture displayed under the circumstances;

3. Create an ImageLoader object. Its constructor receives two parameters. The first parameter is a RequestQueue object, and the second parameter is an ImageCache class object. The ImageCache class implements two methods, which are putBitmap and getBitmap. The cache we mentioned earlier is implemented here. In the putBitmap method, the bitmap object received by the request is added to the cache, and the getBitmap method obtains the image added to the cache in the putBitmap method through the requested URL. For the implementation of cache , LruCache can be used . LruCache is a generic class. It is a cache class provided by Android 3.1. It uses a LinkedHashMap to store external cache objects in a strong reference manner. It provides get and put methods. To complete the cache acquisition and addition operations. If you want to achieve disk cache, you can also use DiskLruCache , which is not part of the AndroidSDK, use DiskLruCache to download it in advance, here will not introduce the use of cache in detail, because today we focus on the use of volley.

4. Finally, call the get () method of ImageLoader to load the image. The last two parameters of the get method are to set the maximum length and width of the picture. By default, 0 means no compression, according to the size of the original picture.

 

Published 106 original articles · praised 37 · 80,000 views

Guess you like

Origin blog.csdn.net/lyz_zyx/article/details/72870418