Volley Home Https://android.googlesource.com/platform/frameworks/volley
http://www.youtube.com/watch?v=yhv8l9F44qo&feature=player_embedded
1. What is volley
On Google I/O 2013, volley released volley. Before that, when we needed to communicate with the Internet in our programs, we used a lot more than
- Asynctaskloader
- HttpURLConnection
- Asynctask
- HTTPClient (Apache), etc.
Volley is a network communication library on the Android platform that makes network communication faster, simpler, and more robust.
Origin of volley name: a burst or emission of many things or a large amount at once
In Google Io's speech, the map is a picture of fire arrows, a bit like a meteor. See
In fact, from this picture, we can also see that the volley is particularly suitable for a small amount of data but frequent communication scenes.
Background introduced by volley
In the past, we could face a lot of troubling problems. For example, the previous steps for downloading pictures from the web might be such a process:
- Begins the reading of the image in Listadapter#getview ().
- through the mechanism of asynctask and other mechanisms to use httpurlconnection from the server to the picture resources
- Set the properties of the corresponding ImageView in Asynctask#onpostexecute ().
In the volley, only one function is required, see the following example in detail.
For example, when the screen rotates, it can sometimes cause data to be obtained again from the network. In order to avoid this unnecessary network access, we may need to write a lot of our own processing for various situations, such as cache or something.
Again, for example, when the ListView, we rolled too fast, may cause some network requests to return, have already rolled over the position, there is no need to display in the list, although we can use the Viewholder to maintain the URL and so on to prevent two times achieved, But the data that has not been required will still waste the resources of the system.
Features provided by volley
Simply put, it provides the following handy features:
- Asynchronous download of JSON, image, etc.;
- Ordering of network requests (scheduling)
- Priority handling of network requests
- Cache
- Multi-level cancellation requests
- Interaction with activity and life cycle (simultaneous cancellation of all network requests at end of activity)
Pre-use preparation
The introduction of volley is very simple, first of all, from the GIT library first cloned one down:
View
Then compile it into a jar package and import it into your own project.
Note that this library requires a minimum SDK version of Froyo, which is to set at least android:minsdkversion to 8 or more.
Use an example of the simplest GET request
This example is simple, get the JSON object from the network and print it out.
Mqueue = Volley.newrequestqueue (Getapplicationcontext ()); Mqueue.add (New Jsonobjectrequest (method.get, URL, null, new Listener () { @Override public void Onresponse (Jsonobject response) { log.d (TAG, "response:" + response.tostring ()); } }, null)); Mqueue.start ();
3.2. Set the image source for ImageView
ImageView is a ImageView instance //Imageloader.getimagelistener The second parameter is the default picture resource ID //The third parameter is the resource ID when the request fails, can be specified as 0 imagelistener listener = Imageloader.getimagelistener (ImageView, Android. R.drawable.ic_menu_rotate, Android. R.drawable.ic_delete); Mimageloader.get (URL, listener);
Imageloader methods need to be called from the main thread.
Using Networkimageview
Volley provides a new control Networkimageview to replace the traditional ImageView, the Picture property of this control can be
Mimageview.setimageurl (URL, imageloader)
To set. Furthermore, this control automatically cancels the network request when it is detach from the parent control, that is, without worrying about the lifecycle of the associated network request.
The sample code is as follows:
Mimageloader = new Imageloader (Mrequestqueue, New Bitmaplrucache ()); ... ... if (holder.imagerequest! = null) { holder.imageRequest.cancel (); }
Note that the ImageView control is not used here, but instead volley the newly provided com.android.volley.NetworkImageView.
In addition, note here:
Mimageloader = new Imageloader (Mrequestqueue, New Bitmaplrucache ()); <span style= "color: #000000;" ><a target=_blank target= "_blank" href= "http://blog.csdn.net/t12x3456/article/details/9221611#" class= " Viewsource "title=" View Plain "style=" text-decoration:none; Background-color:inherit; Border:medium none; padding:1px; margin:0px 10px 0px 0px; font-size:9px; Display:inline-block; width:16px; height:16px; Text-indent: -2000px; " >ew plain</a></span>
The second parameter of the Imageloader constructor is an instance of a imagecache (strictly speaking, an instance of a specific class that implements the Imagecache interface)
Imagecache is defined as follows (in Imageloader.java):
/** * Simple Cache adapter interface. If provided to the Imageloader, it * 'll be used as a L1 cache before dispatch to volley. Implementations * must not block. Implementation with a LruCache is recommended. * /public interface Imagecache {public Bitmap getbitmap (String URL); public void Putbitmap (String url, Bitmap Bitmap); }
The following URL is an LRU cache implementation example, please refer to:
Https://github.com/suwa-yuki/VolleySample/blob/master/src/jp/classmethod/android/sample/volley/BitmapCache.java
Use your own customized request
We can also customize our request according to our needs by inheriting the request.
@Override protected Response 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)); } }
This snippet of code is excerpted from:https://gist.github.com/ficusk/5474673
The Gson (Com.google.gson.Gson) used inside is a library of JSON serialization and deserialization that can be converted between JSON and the Java model object.
The following are examples of using custom request:
Mrequestqueue.add (new Gsonrequest (URL, listresponse.class, NULL, new Listener () {public void Onresponse ( Listresponse response) { appenditemstolist (response.item); Notifydatasetchanged ();}}}
Architecture design of Volley
Volley uses the line pool as the infrastructure, mainly divided into the main thread, the cache thread and the network thread.
Both the main thread and the cache thread have only one, and the networkdispatcher thread can have multiple, which solves the problem of parallelism. Such as:
If a network request is initiated within an activity, and if the activity is ended when the network request has not yet returned, then we need to write the following code as defense:
@Override public void OnPostExecute (Result r) { if (getactivity () = = null) { return; } // ...
After the activity is terminated, if you continue to use the context and so on, in addition to the innocent waste of CPU, battery, network and other resources, may also cause the program crash, so we need to deal with this situation.
With volley, we can cancel all or some of the unfinished network requests while the activity is stopped.
All requests in the volley are returned to the main process, and if certain requests are canceled in the main process, the requests will not be returned to the main thread.
For example, you can cancel an operation for some request y
@Override public void OnStop () {for (Request <?> req:minflightrequests) { req.cancel () } : . }
Or, cancel all requests in this queue:
@Override pubic void OnStop () { mrequestqueue.cancelall (this); ... }
You can also terminate certain requests based on Requestfilter or tag:
@Override public void OnStop () { mrequestqueue.cancelall (new Requestfilter () {}) ... or Mrequestqueue.cancelall (new Object ()); ...
Summarize
From the speech example, volley should be a simplification of some of the development of network communications, especially for the following two scenarios:
- JSON object
- Picture loading
But this thing also has the impractical place, for example big data (large payloads), the stream media, these case, also need to use the primitive method, for example download Manager and so on.
Android network communication Framework Volley introduction