Friday, June 12, 2015

Android Volley Framework



Introduction:
Volley is an android library released by Google that can make your life easier when dealing with network operations.It makes networking for Android apps easier and most importantly, faster.It manages the processing and caching of network requests and it saves developers valuable time from writing the same network call/cache code again and again. And one more benefit of having less code is less number of bugs.
There are 2 main classes:
1. Request queue
2. Request
Request queue: It is the interest you use for dispatching requests to the network, you can make a request queue on demand if you want, but typically, you’ll instead create it early on, at startup time, and keep it around and use it as a Singleton.
Request: It contains all the necessary details for making web API call. For example: which method to Use (GET or POST), request data to pass, response listener, errorlistener.
Volley architecture :

Sending a Simple Request :

At a high level, you use Volley by creating a RequestQueue and passing it Request objects. The RequestQueue manages worker threads for running the network operations, reading from and writing to the cache, and parsing responses. Requests do the parsing of raw responses and Volley takes care of dispatching the parsed response back to the main thread for delivery.

Add the INTERNET Permission :


To use Volley, you must add the android.permission.INTERNET permission to your app's manifest. Without this, your app won't be able to connect to the network.

Use newRequestQueue :


Volley provides a convenience method Volley.newRequestQueue that sets up a RequestQueue for you, using default values, and starts the queue. For example:
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 delivers parsed responses on the main thread. Running on the main thread is convenient for populating UI controls with received data, as you can freely modify UI controls directly from your response handler, but it's especially critical to many of the important semantics provided by the library, particularly related to canceling requests.
See Setting Up a RequestQueue for a description of how to set up a RequestQueue yourself, instead of using the Volley.newRequestQueue convenience method.

Send a Request :


To send a request, you simply construct one and add it to the RequestQueue with add(), as shown above. Once you add the request it moves through the pipeline, gets serviced, and has its raw response parsed and delivered.
When you call add(), Volley runs one cache processing thread and a pool of network dispatch threads. When you add a request to the queue, it is picked up by the cache thread and triaged: if the request can be serviced from cache, the cached response is parsed on the cache thread and the parsed response is delivered on the main thread. If the request cannot be serviced from cache, it is placed on the network queue. The first available network thread takes the request from the queue, performs the HTTP transaction, parse the response on the worker thread, writes the response to cache, and posts the parsed response back to the main thread for delivery.
Note that expensive operations like blocking I/O and parsing/decoding are done on worker threads. You can add a request from any thread, but responses are always delivered on the main thread.

Cancel a Request :


To cancel a request, call cancel() on your Request object. Once cancelled, Volley guarantees that your response handler will never be called. What this means in practice is that you can cancel all of your pending requests in your activity's onStop() method and you don't have to litter your response handlers with checks forgetActivity() == null, whether onSaveInstanceState() has been called already, or other defensive boilerplate.
To take advantage of this behavior, you would typically have to track all in-flight requests in order to be able to cancel them at the appropriate time. There is an easier way: you can associate a tag object with each request. You can then use this tag to provide a scope of requests to cancel. For example, you can tag all of your requests with the Activity they are being made on behalf of, and call requestQueue.cancelAll(this) fromonStop(). Similarly, you could tag all thumbnail image requests in a ViewPager tab with their respective tabs and cancel on swipe to make sure that the new tab isn't being held up by requests from another one.
Here is an example that uses a string value for the tag:
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);
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);
   }
}
Take care when canceling requests. If you are depending on your response handler to advance a state or kick off another process, you need to account for this. Again, the response handler will not be called.

Advantages of using Volley:

  1. Volley automatically schedule all network requests. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from web.
  2. Supports request prioritization. This means that you can load content depending of priorities, for example the main content could have a high priority, but the images a low priority.
  3. Volley provides transparent disk and memory cache that allows for quick reloading of data. Transparent cache means that the caller doesn’t have to know about the existence of the cache. That is, the cache is implemented automatically. You do, however, have the possibility to disable the caching.
  4. Volley provides powerful cancellation request API. It means that you can cancel a single request or cancel requests depending on some filters or you can set blocks or scopes of requests to cancel.
  5. Volley provides powerful customization abilities.
  6. Volley provides Debugging and tracing tools.
  7. Besides the great features that Volley comes with, you don’t have to use it for everything. Volley is great for RPC-style network operations that populate UI, a typical example would be loading thumbnail images into a ListView, but not very good for streaming operations like downloading a video or mp3.

3 comments:

  1. Hi Narasimha,

    Thanks for sharing this wounder full information.

    Keep posting...

    ReplyDelete
  2. Very useful information. Thanks for sharing.
    Keep posting... cheers......

    ReplyDelete