The Use and Introduction of Volley

Posted by SQL Maestro on Sat, 25 May 2019 01:56:02 +0200

1. Brief introduction

Because it's a brief introduction, there's no complicated explanation here.

Volley is a network framework produced by the google method. It was released at the Goolge IO 2013 conference. Now, it can be seen in Android development Training. Training Introduces the Original Address This address needs to be turned over.

In the enclosed video address, also need to turn over the wall. Volley: Easy, Fast Networking for Android.

Although the current project may be all used is Retrofit But it's still necessary to learn about Volley. Generally speaking, Android's father, google, produced it, and the code is still in maintenance as far as it is concerned.

2. Transmitting Network Data Using Volley

Volley is an HTTP library that makes the network of Android applications easier and, most importantly, faster.

Volley can be found on Github Code

Volley has the following characteristics:

  • 1. Automatic scheduling of network requests
  • 2. Supporting multiple concurrent network connections
  • 3. Hard Disk and Memory Cache with Standard HTTP Cache Consistency
  • 4. Supporting Request Priority
  • 5. Supporting request cancellation API can cancel a single request and also support setting blocks or ranges of requests to be cancelled.
  • 6. Easier customization
  • 7. Strong sequentiality ensures that asynchronously acquired data properly populates your UI
  • 8,Debugging and tracing tools.

Volley is good at RPC-TYPE operations for filling UI s, such as crawling search results pages as structured data. It is easy to integrate with any protocol and provides built-in support for outputting raw strings, images, and JSON. It allows you to focus more on specific business logic functions.

Volley is not suitable for large downloads or streaming operations because it holds all Respense information in memory for easy parsing. For large downloads, consider other ways, such as Download Manager.

If you want to integrate Volley into your project, you can add the following code

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

Of course, you can also clone the code and add it to the project as a module.

git clone https://github.com/google/volley

Sending a Simple Request

2-1. Add INTERNET permissions

 <uses-permission android:name="android.permission.INTERNET" />

2-2. Use RequestQueue

Volley provides a convenient way for Volley.newRequestQueue to configure RequestQueue, which of course uses default values to open the queue. Here are some examples.

final TextView mTextView = (TextView) findViewById(R.id.text);
...

// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";

// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Display the first 500 characters of the response string.
        mTextView.setText("Response is: "+ response.substring(0,500));
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        mTextView.setText("That didn't work!");
    }
});
// Add the request to the RequestQueue.
queue.add(stringRequest);

Volley always presents the parsed return results in the main thread, which makes it easy to do UI-related filling operations. You can easily get the data to modify the UI control directly. It also provides many useful functions, such as canceling a request.

2-3. Sending requests

To send a request, you just need to construct a request and add it to the RequestQueue through the RequestQueue#add() method. After adding the request, it will move through the pipeline to get the service and parse and distribute its original corresponding.

When you call the add() method, Volley runs a cache processing thread and a network scheduling thread pool. When you add a request to the queue, it will be judged by the cache thread. If the corresponding cache service can work, that is to say, the cache of the request exists and does not expire, the cache thread parses and distributes the result back to the main thread (UI thread). If it cannot be retrieved from the cache (including cache expiration), it is placed in the message queue. A network task thread processes requests, executes HTTP transactions, parses the returned results on the worker thread, writes the returned results to the cache, and distributes the parsed results back to the main thread.

note: Time-consuming operations such as blocking IO and parsing data are done in the worker thread. You can add a request from any thread, but the response is always in the main thread.

2-4. Cancellation of requests

Cancel a request and call cancel() on your Request object. Once cancelled, Volley ensures that your response result processing and distribution will never be invoked differently. (Personally, regardless of the result of your network request processing, once cancelled, the processing responsible for the result distribution will be interrupted.) This means that you can cancel your unexecuted request in onStop, and you don't have to check getActivity() == null in the return section of your request processing at all (this processing logic won't go anyway).

To use this behavior, you should track all your in-flight requests (which should be understood as all requests that have been requested but have not yet received the results of the requests) in order to cancel them at the right time. Here's a simple way: you can associate a tag with a request, and then you can use this tag to provide a range of cancellations.

Here is an example that uses a string value for the tag:

  • 1,Define your tag and add it to your requests.
public static final String TAG = "MyTag";
StringRequest stringRequest; // Assume this exists.
RequestQueue mRequestQueue;  // Assume this exists.

// Set the tag on the request.
stringRequest.setTag(TAG);

// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);
  • 2,In your activity's onStop() method, cancel all requests that have this tag.
@Override
protected void onStop () {
    super.onStop();
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(TAG);
    }
}

When canceling a request, be aware that if your request results need to advance a state or another process, you should understand that the corresponding processing (state or another process-related operation) will not be invoked either.

3. Setting Up a RequestQueue (configuring RequestQueue)

3-1. Setting up Network and Caching

A RequestQueue does two things: transmitting network requests and processing data caching. Default implementations are provided in Volley's toolbox:

DiskBaseCache provides a file that corresponds to the index in memory one by one. Basic Network provides an HTTP-based network transport protocol client.

Basic Network is Volley's default network implementation. A network must initialize the link network with your application using HTTP client, usually HttpUrlConnection.

The following code snippet shows how to set up RequestQueue

RequestQueue mRequestQueue;

// Instantiate the cache
Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap

// Set up the network to use HttpURLConnection as the HTTP client.
Network network = new BasicNetwork(new HurlStack());

// Instantiate the RequestQueue with the cache and network.
mRequestQueue = new RequestQueue(cache, network);

// Start the queue
mRequestQueue.start();

String url ="http://www.example.com";

// Formulate the request and handle the response.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        // Do something with the response
    }
},
    new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // Handle error
    }
});

// Add the request to the RequestQueue.
mRequestQueue.add(stringRequest);

// ...

If you only want to make a request once without needing a thread pool, you can create a RequestQueue anywhere you need, and call stop() after the data returns. A more common approach is to use Volley.newRequestQueue() directly to execute a simple request and keep RequestQueue singleton in your application.

3-2. Use the singleton model

To make your network requests available throughout the life cycle of the application, you can set RequestQueue as a single mode.

One thing to note is that RequestQueue must be initialized using Application Context instead of Activity Context, which ensures that RequestQueue is valid throughout the life cycle of the application.

public class MySingleton {
    private static MySingleton mInstance;
    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static Context mCtx;

    private MySingleton(Context context) {
        mCtx = context;
        mRequestQueue = getRequestQueue();

        mImageLoader = new ImageLoader(mRequestQueue,
                new ImageLoader.ImageCache() {
            private final LruCache<String, Bitmap>
                    cache = new LruCache<String, Bitmap>(20);

            @Override
            public Bitmap getBitmap(String url) {
                return cache.get(url);
            }

            @Override
            public void putBitmap(String url, Bitmap bitmap) {
                cache.put(url, bitmap);
            }
        });
    }

    public static synchronized MySingleton getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new MySingleton(context);
        }
        return mInstance;
    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            // getApplicationContext() is key, it keeps you from leaking the
            // Activity or BroadcastReceiver if someone passes one in.
            mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
        }
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        getRequestQueue().add(req);
    }

    public ImageLoader getImageLoader() {
        return mImageLoader;
    }
}

The following is an example of use:

// Get a RequestQueue
RequestQueue queue = MySingleton.getInstance(this.getApplicationContext()).
    getRequestQueue();

// ...

// Add a request (in this example, called stringRequest) to your RequestQueue.
MySingleton.getInstance(this).addToRequestQueue(stringRequest);

4. Making a Standard Request

Volley built-in supports the following request types:

StringRequest: Specifies a url that requests the result of the string type.

JsonObjectRequest and JsonArrayRequest, specifying a url, return the result in JSON or JSONAarray format.

The following example is shown using JsonObjectRequest:

TextView mTxtDisplay;
ImageView mImageView;
mTxtDisplay = (TextView) findViewById(R.id.txtDisplay);
String url = "http://my-json-feed";

JsonObjectRequest jsObjRequest = new JsonObjectRequest
        (Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {
        mTxtDisplay.setText("Response: " + response.toString());
    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub

    }
});

// Access the RequestQueue through your singleton class.
MySingleton.getInstance(this).addToRequestQueue(jsObjRequest);

5. Implementing a Custom Request

Volley's Toolbox provides network requests, default caching implementations, and several request modes. If these do not meet your actual needs, Volley also supports custom implementations.

5-1. Custom Network Request

If you want to implement network requests on your own, you need the following steps:

  • 1. Inherit Request < T>, where generic T is the return result type after processing. If you expect the type after parsing to be String, you may need to write Request. The specific implementation can be found in Volley Toolbox.
  • 2. Implement the abstract methods parseNetworkResponse() and delivery Response.

parseNetworkResponse
The main purpose of this method is to parse the returned result set.

@Override
protected Response<T> parseNetworkResponse(
        NetworkResponse response) {
    try {
        String json = new String(response.data,
        HttpHeaderParser.parseCharset(response.headers));
    return Response.success(gson.fromJson(json, clazz),
    HttpHeaderParser.parseCacheHeaders(response));
    }
    // handle errors
...
}

The parameter NetworkResponse of parseNetworkResponse contains HTTP status code, header information and so on.

deliverResponse

protected void deliverResponse(T response) {
        listener.onResponse(response);

5-2,Example: GsonRequest

public class GsonRequest<T> extends Request<T> {
    private final Gson gson = new Gson();
    private final Class<T> clazz;
    private final Map<String, String> headers;
    private final Listener<T> listener;

    /**
     * Make a GET request and return a parsed object from JSON.
     *
     * @param url URL of the request to make
     * @param clazz Relevant class object, for Gson's reflection
     * @param headers Map of request headers
     */
    public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
            Listener<T> listener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.clazz = clazz;
        this.headers = headers;
        this.listener = listener;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        return headers != null ? headers : super.getHeaders();
    }

    @Override
    protected void deliverResponse(T response) {
        listener.onResponse(response);
    }

    @Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
        try {
            String json = new String(
                    response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(
                    gson.fromJson(json, clazz),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JsonSyntaxException e) {
            return Response.error(new ParseError(e));
        }
    }
}

Topics: network JSON Android Google