Android Volley Network Communication Framework (Google), androidvolley

Source: Internet
Author: User

Android Volley Network Communication Framework (Google), androidvolley

Volley home https://android.googlesource.com/platform/frameworks/volley

Http://www.youtube.com/watch? V = yhv8l9F44qo & feature = player_embedded

1. What is Volley?

Before that, when we need to communicate with the network in the program, we generally use AsyncTaskLoader, HttpURLConnection, AsyncTask, HTTPClient (Apache), etc, volley was released at Google I/O 2013 this year. Volley is a network communication library on the Android platform, which enables faster, simpler, and more robust network communication.
This is the origin of the Volley name: a burst or emission of volume things or a large amount at once
In a speech by Google IO, the image is like a meteor. See

In fact, from this figure, we can also see that Volley is particularly suitable for scenarios with small data volumes but frequent communication.

1.1. Background introduced by Volley
In the past, we may face the following problems.

For example, the previous steps for downloading images from the Internet may be as follows:

  • Start reading the image in ListAdapter # getView.
  • Use AsyncTask and other mechanisms to use HttpURLConnection to remove image resources from the server
  • Set the attributes of the corresponding ImageView in AsyncTask # onPostExecute.

In Volley, only one function is required. For details, see the following example.

For example, when the screen is rotated, sometimes the data is retrieved from the network again. To avoid such unnecessary network access, we may need to write a lot of processing for various situations, such as cache or something.

In addition, for example, when ListView is returned, we scroll too fast, which may cause some network requests to return and have already rolled over the current position, and there is no need to display it in the list, although we can use ViewHolder to maintain URLs and so on to prevent them from being obtained twice, the unnecessary data will waste various system resources.

1.2. features provided by Volley
To put it simply, it provides the following convenient functions:

  • Asynchronous download of JSON and images;
  • Scheduling)
  • Priority processing of network requests
  • Cache
  • Multi-level cancellation request
  • Interaction with Activity and lifecycle (canceling all network requests at the end of Activity)

2. Preparations before use

Introducing Volley is very simple. First, clone it from the git Library:

[Java]View plaincopy
  1. Git clone https://android.googlesource.com/platform/frameworks/volley

Compile it as a jar package and import it in your project.

Note that the minimum SDK version of this library is Froyo, that is, you must set at least android: minSdkVersion to 8 or above.

3. Example
The following describes how to use Volley.

3.1. Simplest get request
This example is very 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 an ImageView instance.
  2. // The second parameter of ImageLoader. getImageListener is the default image resource id.
  3. // The third parameter is the resource id when the request fails. It can be set to 0.
  4. ImageListener listener = ImageLoader. getImageListener (imageView, android. R. drawable. ic_menu_rotate, android. R. drawable. ic_delete );
  5. MImageLoader. get (url, listener );

All ImageLoader methods must be called from the main thread.

3.3. Use NetworkImageView

Volley provides a new control NetworkImageView to replace the traditional ImageView.

[Java]View plaincopy
  1. MImageView. setImageUrl (url, imageLoader)

. In addition, when the control is detach from the parent control, the network request is automatically canceled, that is, we do not need to worry about the network request lifecycle.
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 the com. android. Volley. NetworkImageView provided by volley.

Note:

[Java]View plaincopy
  1. MImageLoader = new ImageLoader (mRequestQueue, new BitmapLruCache ());

The second parameter of the ImageLoader constructor is an ImageCache instance (strictly speaking, it is 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. * Will be used as an L1 cache before dispatch to Volley. Implementations
  4. * Must not block. Implementation with an 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 provides an lru cache implementation example. For more information, see:

Https://github.com/suwa-yuki/VolleySample/blob/master/src/jp/classmethod/android/sample/volley/BitmapCache.java

3.5. Use your own custom request

We can also customize our own requests based on our own requirements by inheriting requests.

[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

Gson (com. google. gson. Gson) is a JSON serialization and deserialization library, which can be converted between JSON and java model objects.

The following is an example of using a 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. Volley Architecture Design

Volley uses the thread pool as the basic structure, mainly divided into the main thread, cache thread and network thread.
The main thread and cache thread have only one thread, while the NetworkDispatcher thread can have multiple threads, which can solve parallel problems. For example:


If a network request is initiated in an Activity and no results are returned for this network request, if the Activity is completed, we need to write the following code to defend:

[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 among others, in addition to wasting resources such as CPU, battery, and network resources, it may also lead to program crash, we need to deal with this situation.

With Volley, we can cancel all or some unfinished network requests when the Activity is stopped.

All request results in Volley will be returned to the main process. If some requests are canceled in the main process, these requests will not be returned to the main thread.
For example, you can cancel some requests:


[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 some 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 example given in the speech, Volley should simplify the development of network communication, especially for the following two situations:

  • JSON object
  • Image loading

However, this is not practical, such as large payloads and streaming media. In these cases, you also need to use the original method, such as Download Manager.
In short, if you want to write a network program, can you consider using Volley?

Free volley documentation download

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.