Android network communication Framework Volley introduction

Source: Internet
Author: User

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 
    1. 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  
  1. Mqueue = Volley.newrequestqueue (Getapplicationcontext ());
  2. Mqueue.add (new Jsonobjectrequest (method.get, URL, null,
  3. New Listener () {
  4. @Override
  5. public void Onresponse (jsonobject response) {
  6. LOG.D (TAG, "response:" + response.tostring ());
  7. }
  8. }, null));
  9. Mqueue.start ();


3.2. Set the image source for ImageView

[Java]View PlainCopy 
    1. ImageView is a ImageView instance
    2. The second parameter of Imageloader.getimagelistener is the default picture resource ID
    3. The third parameter is the resource ID at the time of the request failure and can be specified as 0
    4. Imagelistener listener = Imageloader.getimagelistener (ImageView, Android. R.drawable.ic_menu_rotate, Android. R.drawable.ic_delete);
    5. 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 
    1. 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  
    1. Mimageloader = New Imageloader (Mrequestqueue, new Bitmaplrucache ());
    2. ... ...
    3. if (holder.imagerequest! = null) {
    4. Holder.imageRequest.cancel ();
    5. }
    6. 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 
    1. 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 
  1. /**
  2. * Simple Cache Adapter interface. If provided to the Imageloader, it
  3. * 'll be used as a L1 cache before dispatch to volley. Implementations
  4. * Must not block. Implementation with a LruCache is recommended.
  5. */
  6. Public interface Imagecache {
  7. Public Bitmap getbitmap (String URL);
  8. public void putbitmap (String url, Bitmap Bitmap);
  9. }


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 
  1. @Override
  2. Protected Response parsenetworkresponse (Networkresponse Response) {
  3. try {
  4. String json = new String (
  5. Response.data, Httpheaderparser.parsecharset (response.headers));
  6. return response.success (
  7. Gson.fromjson (JSON, Clazz), httpheaderparser.parsecacheheaders (response));
  8. } catch (Unsupportedencodingexception e) {
  9. return Response.error (new ParseError (e));
  10. } catch (Jsonsyntaxexception e) {
  11. return Response.error (new ParseError (e));
  12. }
  13. }


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  
    1. Mrequestqueue.add ( new Gsonrequest (URL, listresponse. class, null,
    2. New Listener () {
    3. public void Onresponse (listresponse response) {
    4. Appenditemstolist (Response.item);
    5. Notifydatasetchanged ();
    6. }
    7. }
    8. }

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 
    1. @Override public void OnPostExecute (Result r) {
    2. if (getactivity () = = null) {
    3. return;
    4. }
    5. // ...  
    6. }

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 
    1. @Override
    2. Public void OnStop () {
    3. For (Request <?> req:minflightrequests) {
    4. Req.cancel ();
    5. }
    6. ...
    7. }


Or, cancel all requests in this queue:

[Java]View PlainCopy  
    1. @Override pubic void OnStop () {
    2. Mrequestqueue.cancelall (this);
    3. ...
    4. }


You can also terminate certain requests based on Requestfilter or tag:

[Java]View PlainCopy  
    1. @Override public void OnStop () {
    2. Mrequestqueue.cancelall ( new Requestfilter () {})
    3. ...
    4. //or
    5. Mrequestqueue.cancelall (new Object ());
    6. ...

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.

Android network communication Framework Volley introduction

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.