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
- 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
- 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 an ImageView instance.
- // The second parameter of ImageLoader. getImageListener is the default image resource id.
- // The third parameter is the resource id when the request fails. It can be set to 0.
- ImageListener listener = ImageLoader. getImageListener (imageView, android. R. drawable. ic_menu_rotate, android. R. drawable. ic_delete );
- 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
- 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
- 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 the com. android. Volley. NetworkImageView provided by volley.
Note:
[Java]View plaincopy
- 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
- /**
- * 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 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
- @ 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
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
- MRequestQueue. add (new GsonRequest (url, ListResponse. class, null,
- New Listener (){
- Public void onResponse (ListResponse response ){
- AppendItemsToList (response. item );
- NotifyDataSetChanged ();
- }
- }
- }
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
- @ Override public void onPostExecute (Result r ){
- If (getActivity () = null ){
- Return;
- }
- //...
- }
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
- @ 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 some 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 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