<a target=_blank href= "Https://android.googlesource.com/platform/frameworks/volley" style= "font-family:arial, Helvetica, Sans-serif; Box-sizing:border-box; background-image:initial; background-attachment:initial; Background-color:rgb (255, 255, 255); background-size:initial; background-origin:initial; background-clip:initial; background-position:initial; background-repeat:initial; " >volley</a><span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " > is Google I/O 2013 launch of the network Communications library, before volley launch we will generally choose a more mature third-party network Communications library, </span><span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " >volley is a network communication library on the Android platform that makes network communication faster, simpler, and more robust. </span><span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " > such as:</span>
-
Android-async-http
-
Retrofit
-
Okhttp
They each have the pros and cons, before individuals prefer to use android-async-http, now Google launched the official Internet Communication Library for Android platform, can make network communication faster, simpler, more robust, volley in providing high-performance network communication capabilities, while Network image loading also provides good support, fully meet the needs of simple rest client, we have no reason not to keep up with the trend of the Times
Using volley
Download the volley source code and build the jar package.
$ git clone https://android.googlesource.com/platform/frameworks/volley$ cd volley$ android update project-p$ ant jar
The resulting jar package is then referenced to our project, and the Extras directory contains the current volley source code.
Description
This demo mainly introduces the basic functions commonly used in daily network development, but volley is very extensible and can customize your own network request as needed.
Volley video address: http://www.youtube.com/watch?v=yhv8l9F44qo&feature=player_embedded
The above is in the Google IO speech on the ppt map, from the above picture we can see, volley suitable for fast, simple request (JSON object, picture loading).
Features of the volley:
- 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)
Next, let's learn the simple use of volley to provide me with the API bar.
1. First get a request queue (Requestqueue only need one instance, not like asynctask each use of new one)
Initialize Requestqueue an activity requires only a private void Initrequestqueue () {mqueue = Volley.newrequestqueue ( Getapplicationcontext ());}
2. Implement the volley asynchronous request class (Jsonobjectrequest,jsonarrayrequest,stringrequest,imagerequest)
Because of the difference in usage, I will not give an example, to cite a few typical examples:
The following code is a GET request for Stringrequest :
GET request
private void Loadgetstr (String url) {stringrequest srreq = new Stringrequest (Request.Method.GET, Url,new Strlistener (), n EW Strerrlistener ()) {protected final String Type_utf8_charset = "charset=utf-8";// Override the Parsenetworkresponse method to change the return header parameters to solve the garbled problem//main is to look at the server code, if the server encoding is not UTF-8 then you need to convert, and vice versa do not need @overrideprotected Response <String> Parsenetworkresponse (networkresponse response) {try {String type = Response.headers.get (HTTP. Content_Type), if (type = = null) {type = Type_utf8_charset;response.headers.put (HTTP. Content_Type, TYPE);} else if (!type.contains ("UTF-8")) {type + = ";" + type_utf8_charset;response.headers.put (HTTP. Content_Type, TYPE);}} catch (Exception e) {}return super.parsenetworkresponse (response);}}; Srreq.setshouldcache (TRUE); Controls whether to cache Startvolley (srreq);}
The following code is jsonobjectrequest 's postRequest:
Post request private void Loadpostjson (String URL) {//second parameter description://Constructor which defaults to GET if jsonrequest is null, PO st//otherwise.//The default is null for the Get method, otherwise the Post method. Jsonobjectrequest srreq = new Jsonobjectrequest (URL, null,new jsonlistener (), New Strerrlistener ()) {@Overrideprotected Map<string, String> Getparams () throws Authfailureerror {map<string, string> Map = new hashmap<string, Str Ing> (); Map.put ("W", "2459115"), Map.put ("U", "F"); return map;}}; Srreq.setshouldcache (FALSE); Controls whether to cache Startvolley (srreq);}
Everyone look at the words, whether it isJsonobjectreques's Postt or stringrequest get all need to pass in two listener functions one is the successful one is the failure, the successful listener will return the corresponding type of data:
STR request successfully callback private class Strlistener implements listener<string> {@Overridepublic void Onresponse (String arg0) { LOG.E (Tag, arg0);}} Gson request successfully callback private class Gsonlistener implements listener<errorrsp> {@Overridepublic void Onresponse (ERRORRSP arg0) {Toast.maketext (Mcontext, arg0.tostring (), Toast.length_long). Show ();}} Shared failure callback Private class Strerrlistener implements Errorlistener {@Overridepublic void Onerrorresponse (Volleyerror arg0) { Toast.maketext (Mcontext,volleyerrorhelper.getmessage (arg0, Mcontext), Toast.length_long). Show ();}}
Next isimagerequest
/** * The third and fourth parameters are used to specify the maximum width and height of the allowed picture, if the specified network picture width or height is greater than the maximum value here, the picture will be compressed, * specified as 0, it means that no matter how large the picture, will not be compressed. * * @param URL * Image address * @param listener * @param maxWidth * Specify the maximum width allowed for the picture * @param maxheight * Specify the maximum height allowed for the picture * @param decodeconfig * Specify the color properties of the picture, bitmap.config the following constants. * @param errorlistener */private void Getimagerequest (final ImageView IV, String URL) {imagerequest imreq = new Imagerequest (URL, new listener<bitmap> () {@Overridepublic void O Nresponse (Bitmap arg0) {iv.setimagebitmap (arg0);}}, Max, Bitmap.Config.ARGB_8888, New Strerrlistener ()); Startvolley (imreq);}
See now people will be puzzled to write so many different types of request exactly how to run? Take a look at:
Add and start request private void Startvolley (Request req) {//Set timeout time//Req.setretrypolicy (new Defaultretrypolicy (1, 1.0f) );//The request is added to the queue Mqueue.add (req);//Start Request Mqueue.start ();}
Volley not only provides the way these requests are made, but also provides some methods and controls for loading pictures:
For example, we need to load a list of many images we can use volley to provide us with Imageloader ( Imageloader is more efficient than imagerequest, because it not only caches images, You can also filter out duplicate links to avoid sending requests repeatedly. )
public class Imageadapter extends arrayadapter<string> {private Requestqueue mqueue; Private Imageloader Mimageloader; Public Imageadapter (context context, list<string> objects) {Super (context, 0, objects); Mqueue = Volley.newrequestqueue (GetContext ()); Mimageloader = new Imageloader (Mqueue, New Bitmapcache ()); } @Override public View getView (int position, view Convertview, ViewGroup parent) {String URL = getItem ( position); ImageView ImageView; if (Convertview = = null) {ImageView = new ImageView (GetContext ()); } else {ImageView = (ImageView) Convertview; }//Getimagelistener (ImageView control object, default picture address, failed image address); Imagelistener listener = Imageloader.getimagelistener (ImageView, Android. R.drawable.ic_menu_rotate, Android. R.drawable.ic_delete); Get (image address, listener, wide, high); Automatically help you to handle the picture of the width of the big picture of the Oom no longer afraid of mimageloader.get (URL, listener,100,200); return IMAgeview; }}And of course you need to rewriteImagecache This class//use LRUCache no longer afraid to load multiple pictures oom
public class <span style= "font-family:arial;" >bitmapcache</span><span style= "font-family:arial;" > Extends Lrucache<string, bitmap> implements Imagecache {</span>//LruCache principle: Cache holds a strong reference to limit the amount of content, Whenever item is accessed, the item is moved to the head of the queue. When a new item is added when the cache is full, the item at the end of the queue is recycled. Explanation: Remove the least recently used image memory when exceeding the specified memory value public static int getdefaultlrucachesize () {//Get maximum memory final int maxmemory = (int ) (Runtime.getruntime (). MaxMemory ()/1024); Get one-eighth of the memory to do the picture memory cache final int cacheSize = MAXMEMORY/8; return cacheSize; } public Bitmaplrucache () {This (getdefaultlrucachesize ()); } public Bitmaplrucache (int sizeinkilobytes) {super (sizeinkilobytes); } @Override protected int sizeOf (String key, Bitmap value) {return value.getrowbytes () * Value.getheight ()/ 1024; } @Override Public Bitmap getbitmap (String URL) {return get (URL); } @Override public void Putbitmap (String url, Bitmap Bitmap){Put (URL, bitmap); }}
Volley also provides a control to load a pictureCom.android.volley.NetworkImageView. ( This control automatically cancels the network request when it is detach from the parent control, that is, without worrying about the lifecycle of the related network request, And Networkimageview will automatically compress the picture based on the width and heigh you set for the picture without generating much memory, and Networkimageview using the list will not be a picture error )
<com.android.volley.toolbox.networkimageview android:id= "@+id/network_image_view" android:layout_ Width= "100DP" android:layout_height= "100DP"/>
How to use:
private void Networkimageviewuse (Networkimageview IV, String URL) {imageloader imloader = new Imageloader (mqueue, New BITM Aplrucache ()); Iv.setdefaultimageresid (R.drawable.ic_launcher); Iv.seterrorimageresid (R.drawable.ic_launcher); Iv.setimageurl (URL, imloader);}
We say so much is the request, then how to cancel the request?
1.activity automatically destroys all requests when it is self-destruct.
2. set the label for the request:
Request.settag ("My Tag");
Cancel all requests for the specified tag:
Request.cancelall ("My Tag");
architecture Design for volley:
Where the blue part represents the main thread, the green part represents the cache thread, and the orange part represents the network thread. We call the Requestqueue's Add () method in the main thread to add a network request that is first added to the cache queue, and if found to be able to find the corresponding cache result, read the cache and parse it directly and then callback to the main thread. If no results are found in the cache, the request is added to the network request queue, which then processes the sending HTTP request, parses the response result, writes the cache, and recalls the main thread. Then there is the Ym--android network framework volley (actual combat)