About Android network Communication Library volley

Source: Internet
Author: User

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:

?
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.

?
123456789 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

?
12345 // imageView是一个ImageView实例// ImageLoader.getImageListener的第二个参数是默认的图片resource id// 第三个参数是请求失败时候的资源id,可以指定为0ImageListener 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

?
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:

?
12 NetworkImageView view = (NetworkImageView) findViewById(R.id.network_image_view);view.setImageUrl(url, newImageLoader(mQueue, newBitmapCache()));

3.4. Using Imageloader

?
1234567 mimageloader =  new imageloader (mrequestqueue,  new bitmaplrucache ()); ...    if ( Holder.imagerequest!=  null ) { Code class= "Java Spaces" >     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:

?
1 mImageLoader = newImageLoader(mRequestQueue, newBitmapLruCache());

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):

?
123456789 /** * Simple cache adapter interface. If provided to the ImageLoader, it * will be used as an L1 cache before dispatch to Volley. Implementations * must not block. Implementation with an 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.

?
12345678910111213 @Overrideprotected 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:

?
12345678 mRequestQueue.add( new GsonRequest(url, ListResponse.classnull,    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.
For specific reference, this image is excerpted from Google I/O presentations

Main Thread

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:

?
123456 < Code class= "Java Color1" > @Override public void onpostexecute (Result R) {       if (getactivity () ==  null ) {           return &NBSP;&NBSP;&NBSP;&NBSP; } &NBSP;&NBSP;&NBSP;&NBSP; //...

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:

?
1234567 @Overridepublicvoid onStop() {    for(Request <?> req : mInFlightRequests) {        req.cancel();    }    ...}

Or, cancel all requests in this queue:

?
1234 @Overridepubic voidonStop() {    mRequestQueue.cancelAll(this);    ...}

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

?
123456 < Code class= "Java Color1" > @Override public void onstop () { &NBSP;&NBSP;&NBSP;&NBSP; mrequestqueue.cancelall (  new requestfilter () {}) &NBSP;&NBSP;&NBSP;&NBSP; ... &NBSP;&NBSP;&NBSP;&NBSP; //or &NBSP;&NBSP;&NBSP;&NBSP; mrequestqueue.cancelall ( new object ()); &NBSP;&NBSP;&NBSP;&NBSP; ...

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?
More content can be obtained from the source code, see the Appendix in the following connection 1.

Appendix, Reference Link:
1. Volley Home Https://android.googlesource.com/platform/frameworks/volley
2. Google I/O volley speech http://www.youtube.com/watch?v=yhv8l9F44qo&feature=player_embedded
3. Android Tips #51 記憶域ネットワーク communication? キャッシュ Hishinuma をより speed bootcut, simple single occupies Natsumi Sato install できるライブラリ "Volley" ってみたhttp://dev.classmethod.jp/smartphone/android/ android-tips-51-volley/
4. Google I/O 2013–android:volley:easy, Fast Networking for Android http://y-anz-m.blogspot.jp/2013/05/google-io-2013 -android-volley-easy-fast.html?m=1

From: http://liubin.org/2013/05/27/android-volley-at-a-glance/

About Android network Communication Library volley

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.