Volley Home Https://android.googlesource.com/platform/frameworks/volley
http://www.youtube.com/watch?v=yhv8l9F44qo&feature=player_embedded
1. What is volley
Before this, we need to communicate with the network in the program, the general use of Things is asynctaskloader,httpurlconnection,asynctask,httpclient (Apache), etc., this year's Google I/O On 2013, Volley was released. Volley is a network communication library on the Android platform that makes network communication faster, simpler, and more robust.
This is the origin of the 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.
1.1. Background introduced by volley
In the past, we may face a lot of problems as follows.
For example, the previous steps for downloading pictures from the Internet might be such a process:
- Start reading the image in Listadapter#getview ().
- Use HttpURLConnection to go from server to picture resources through asynctask and other mechanisms
- 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.
1.2. 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)
2. Pre-use preparation
The introduction of volley is very simple, first of all, from the GIT library first cloned one down:
[Java]View Plaincopy
- git clone https://android.googlesource.com/platform/frameworks/volley
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.
3. Examples of Use
Here's a quick look at how to use volley
3.1. The simplest GET request
This example is simple, get the JSON object from the network and print it out.
[Java]View Plaincopy
- 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
[Java]View Plaincopy
- ImageView is a ImageView instance
- The second parameter of Imageloader.getimagelistener is the default picture resource ID
- The third parameter is the resource ID at the time of the request failure and 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.
3.3. Using Networkimageview
Volley provides a new control Networkimageview to replace the traditional ImageView, the Picture property of this control can be
[Java]View Plaincopy
- 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:
[Java]View Plaincopy
- Mimageloader = New Imageloader (Mrequestqueue, new Bitmaplrucache ());
- ... ...
- if (holder.imagerequest! = null) {
- Holder.imageRequest.cancel ();
- }
- Holder.imagerequest = Mimageloader.get (Base_ur + Item.image_url, Holder.imageview, r.drawable.loading, R.DRAWABLE.ERROR);
Note that the ImageView control is not used here, but instead volley the newly provided com.android.volley.NetworkImageView.
In addition, note here:
[Java]View Plaincopy
- Mimageloader = New Imageloader (Mrequestqueue, new Bitmaplrucache ());
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):
[Java]View Plaincopy
- /**
- * 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
3.5. Use your own customized request
We can also customize our request according to our needs by inheriting the request.
[Java]View Plaincopy
- @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 code excerpt 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:
[Java]View Plaincopy
- Mrequestqueue.add ( new Gsonrequest (URL, listresponse. class, null,
- New Listener () {
- public void Onresponse (listresponse response) {
- Appenditemstolist (Response.item);
- Notifydatasetchanged ();
- }
- }
- }
4. 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:
[Java]View Plaincopy
- @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:
[Java]View Plaincopy
- @Override
- Public void OnStop () {
- For (Request <?> req:minflightrequests) {
- Req.cancel ();
- }
- ...
- }
Or, cancel all requests in this queue:
[Java]View Plaincopy
- @Override pubic void OnStop () {
- Mrequestqueue.cancelall (this);
- ...
- }
You can also terminate certain requests based on Requestfilter or tag:
[Java]View Plaincopy
- @Override public void OnStop () {
- Mrequestqueue.cancelall ( new Requestfilter () {})
- ...
- //or
- Mrequestqueue.cancelall (new Object ());
- ...
5. Summary
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.
In short, if you want to write a network program, is it possible to consider starting to use volley?
Google IO2013 Network framework volley presentation PDF download: http://download.csdn.net/detail/t12x3456/5686041
- Previous Android save picture to system and related problems solution
- Next Android use Localbroadcastmanager to solve broadcastreceiver security issues
Android network Communication Framework Volley introduction (Google IO 2013)