Basic use of volley

Source: Internet
Author: User
Tags net thread
Volley is a communication framework launched by Google at the I/O Conference in 2003, combined with the advantages of asynchttpclient and universal-image-loader, This simplifies the use of HTTP and the magical ability to asynchronously load images. The HTTP implementation in Android mainly includes httpurlconnection and httpclient. Google's selection of the two in the blog shows that we recommend the HTTP implementation in the ginger pie (API level = 9) java httpurlconnection is used in later versions and Apache httpclient is used in earlier versions, which is also clearly reflected in the volley framework. Obtain volley
git clone https://android.googlesource.com/platform/frameworks/volley
Compile it into a jar file and add it to libs. 1. Simple request (taking stringrequest as an example)The most important part of HTTP Communication should be sending requests and receiving responses. Therefore, volley's core class is requestqueue, a request queue. It is responsible for managing working threads, reading and writing caches, parsing, and distributing responses (specific operations are implemented by specific classes ), HTTP requests to be sent will first be gathered here to wait for the working thread to implement the request. Requestqueue can be regarded as an aircraft carrier with full HTTP requests, and the working thread is a catapult. Therefore, according to the plane departure steps, we can guess the simple steps of using volley for HTTP Communication: 1. obtain requestqueue (obtain an aircraft carrier, which can be self-built or commissioned by another operator, as mentioned below) 2. instantiate a request (get an airplane and you know there are many types of planes) 3. add the request to requestqueue and wait for the worker thread to send it out (lift the plane from the hangar to the departure deck, and wait for the catapult to throw it out) the plane for departure-send a GET request following the steps above, the first step is to create a request queue. The simplest method is to use volley. newrequestqueue () is a very convenient static method. By default, we implement all the things we need (network and cache, which are implemented by default in volley ), it returns a running requestqueue (equivalent to someone else helping build an aircraft carrier ). After that, we only need to set the response listening interface of the request, and add the request to this queue, so that we can wait for the response data to knock on the door. The following is the sample code in the Google document:
1 // initialize a request queue 2 requestqueue queue = volley. newrequestqueue (this); 3 string url = "http://www.google.com"; 4 5 // create a request 6 stringrequest = new stringrequest (request. method. get, URL, 7 new response. listener () {8 @ override 9 Public void onresponse (string response) {10 // It is safe to operate the UI component here, because this function will be post to the UI thread when the response is returned to execute 11 // here, the response string will be exhausted. 12} 13}, new response. errorlistener () {14 @ override15 public void onerrorresponse (volleyerror error) {16 // What if an error occurs? Cool! And mix them here. 17} 18}); 19 // Add this request to the Request queue 20 queue. Add (stringrequest );
Stringrequest is one of the specific implementations of the request. It indicates that the parsed response data is a string, and similar classes include jsonrequest (including jsonobjectrequest and jsonarrayrequest), imagerequest to meet the basic usage, the usage is similar. The main difference is that the construction parameters are as follows: 1. public stringrequest (INT method, string URL, listener <string> listener, errorlistener); parameter description: request methods (both encapsulated in the method interface of the request) from left to right ), request URL, response listening interface instance, and error listening interface instance.
2. public jsonobjectrequest (INT method, string URL, jsonobject jsonrequest, listener <jsonobject> listener, errorlistener); Public jsonobjectrequest (string URL, jsonobject jsonrequest, listener <jsonobject> listener, errorlistener); parameter description: if it is a GET request, jsonrequest can pass in null. Otherwise, the request method (that is, the second constructor) is not specified) the default value is post. Others are the same as above. 3. Public jsonarrayrequest (string URL, listener <jsonarray> listener, errorlistener); parameter description: Same as above. 4. public imagerequest (string URL, response. listener <bitmap> listener, int maxwidth, int maxheight, config decodeconfig, response. errorlistener); parameter description: decodeconfig is the color attribute of the image. The following values can be used.
Color Attribute (Enumeration type) in bitmap. config)
Alpha_8  
Argb_4444 Argb_8888 is recommended because of its low quality and has been discarded.
Argb_8888 Each pixel is stored in 4 bytes
Rgb_565 Each pixel is stored in 2 bytes. Red occupies 5 places, green occupies 6 places, and blue occupies 5 places.
Take-off fighter planes-send post requests in the same way as above, but how do I load missiles? No, how do I submit the data? Volley calls the getparam () function of the Request class (that is, the parent class of xxxrequest) to obtain parameters when the request method is post (and put and patch, if httpurlconnection is used, call the addbodyifexists () function in hurlstatck to implement getparam (). If you are interested, take a look. Therefore, the POST request is as follows.
1 // initialize a request queue 2 requestqueue queue = volley. newrequestqueue (this); 3 string url = "http://www.google.com"; 4 5 // create a request 6 stringrequest = new stringrequest (request. method. post, URL, 7 new response. listener () {8 @ override 9 Public void onresponse (string response) {10 // here, the string type response for processing the request is 11} 12}, new response. errorlistener () {13 @ override14 public void onerrorresponse (volleyerror error) {15 // handle the error after this 16} 17}) {18 @ override19 protected Map <string, string> getparams () throws authfailureerror {20 21 Map <string, string> map = new hashmap <string, string> (); 22 map. put ("params1", "value1"); 23 map. put ("params2", "value2"); 24 return map25}; 26 // Add this request to the Request queue 27 queue. add (stringrequest );
Regret-there is a cancel () method in the request for canceling the request. You can call this method to cancel the current request. However, it is not necessarily the level at which the request is canceled, however, volley ensures that the response processing functions (onresponse () and onerroeresponse () will not be called. Another way to cancel multiple requests is to call the settag () method of the request before sending the request to add a tag for each request. The parameter of this method is object, so we can use any type as a label. In this way, you can call the cancelall () function of reqiestqueue to cancel a group of tags. A common method is to use the activity or fragment that sends the request as the tag and call cancelall () in onstop (). Ii. Use imageloader to load images   Imageloader is a class that can implement asynchronous image loading, but it is no longer an inheritance or request. Although imageloader is a head beast, it must be summoned in the main thread; otherwise, an error illegalstateexception will be thrown, probably because imageloader needs to directly operate imageview when returning images, it is safe to operate the UI components in the main thread, SO ~ Use imageloader to load images in three steps. create imageloader 2. get an imagelistener object 3. call the get () method of imageloader to obtain the imageloader constructor. The following code is displayed: Public imageloader (requestqueue queue, imagecache ); therefore, to instantiate an imageloader, you need a requestqueue (just created previously) and an imagecache, which is an interface defined internally by imageloader, it is used to implement L1 cache-memory cache (volley has implemented L2 cache-File Cache in requestqueue ). The imageloader does not empty the passed imagecache code before use. An error occurs when null is passed in. If you really don't want to get the memory cache, just implement an imagecache that does nothing. The following code is used:
1 imageloader = new imageloader (mrequestqueue, new imagecache () {2 @ override 3 Public void putbitmap (string URL, Bitmap bitmap) {4} 5 6 @ override 7 public bitmap getbitmap (string URL) {8 return NULL; 9} 10 }); 11 12 // default_image is the placeholder used when the image is being loaded. 13 // error_image is the image displayed when the image fails to be loaded. 14 imagelistener listener = imageloader. getimagelistener (imageview, R. drawable. default_image, R. drawable. error_image); 15imageloader. get ("your image URL", listener );
In addition to imageloader, volley also has an image-loaded artifact networkimageview. The steps are as follows: 1. add a control to the layout file and obtain the instance 2 in Java code. set default_image, error_image, and image URL. The code of an imageloader object is as follows:
1 networkImageView = (NetworkImageView) findViewById(R.id.network_image_view); 2 networkImageView.setDefaultImageResId(R.drawable.default_image);  3 networkImageView.setErrorImageResId(R.drawable.error_image);4 networkImageView.setImageUrl("your image url", imageLoader);  

 

Iii. Google recommended usageThe above is the basic usage of volley, but if an app requires frequent network communication, it is strange to set up multiple requestqueue (who will create a new aircraft carrier because of the need for a temporary plane to take off at sea? How rich is it ), therefore, Google recommends that we instantiate only one requestqueue to cope with frequent HTTP Communication. Of course, we must ensure that the service life of the queue is as long as that of the app. How to implement it? Google also said that the application in the app is not recommended. the oncretae () method instantiates a requestqueue (but it is indeed a simple method). It is best to create a class in the singleton mode, and put all the volley bottles and tanks we need into it, which is more modular. The following is the sample code. In this Code, the most important thing is that requestqueue needs to instantiate the context of the application. Otherwise, it will be rebuilt continuously with the lifecycle of the activity. In fact, pure static usage like asynchttpclient is also good (see: http://loopj.com/android-async-http/ for details) PS: below also implements a simple imagecache
1 Private Static mysingleton minstance; 2 Private requestqueue mrequestqueue; 3 private imageloader mimageloader; 4 Private Static Context mctx; 5 6 private mysingleton (context) {7 mctx = context; 8 mrequestqueue = getrequestqueue (); 9 10 mimageloader = new imageloader (mrequestqueue, 11 new imageloader. imagecache () {12 private final lrucache <string, bitmap> 13 cache = new lrucache <string, bitmap> (20); 14 15 @ override16 public bitmap getbitmap (string URL) {17 return cache. get (URL); 18} 19 20 @ override21 public void putbitmap (string URL, Bitmap bitmap) {22 cache. put (URL, bitmap); 23} 24}); 25} 26 27 public static synchronized mysingleton getinstance (context) {28 If (minstance = NULL) {29 minstance = new mysingleton (context); 30} 31 return minstance; 32} 33 34 public requestqueue getrequestqueue () {35 if (mrequestqueue = NULL) {36 // getapplicationcontext () is the key, which avoids the disadvantages of 37 // activity or broadcastreceiver. 38 mrequestqueue = volley. newrequestqueue (mctx. getapplicationcontext (); 39} 40 return mrequestqueue; 41} 42 43 public <t> void addtorequestqueue (request <t> req) {44 getrequestqueue (). add (req); 45} 46 47 Public imageloader getimageloader () {48 return mimageloader; 49} 50}

 

4. How does volley manage requests?Requestqueue maintains a cache scheduling thread and a network scheduling thread pool (net thread) (Note: This is a pool of sub-threads). When a request is added to the queue, the cache thread filters the request. If the request content can be found in the cache, the cache thread will parse the corresponding content and distribute it to the main thread (UI ). If the request does not exist in the cache, it will be added to another networkqueue. All requests that are actually preparing for network communication are here, the first available net thread will take out a request from networkqueue and throw it to the server. When the response data arrives, the net thread will parse the original response data, write the data to the cache, and return the parsed results to the main thread. For example, if you read the source code, you can divide the source code into four layers, for example, (the rest of the classes can be classified into "convenient tool classes", such as imageloader and clearcacherequest ).

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.