Android volley Google releases a library of tools for network communications

Source: Internet
Author: User

: Git clone Https://android.googlesource.com/platform/frameworks/volley

Or: Https://github.com/mcxiaoke/android-volley


what can volley do?

a network communication library published at the Google I/O conference. handle some network requests, such as data parsing, downloading display pictures.

• Data processing : The processing of data obtained by a network request.

· Image loading: Download and display of Web images.


Use stepsUse Permissions

<uses-permissionandroid:name=" Android.permission.INTERNET "/>

< uses-permission android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />


initializing the request queue

Requestqueue Mrequestqueue = volley.newrequestqueue (context context);


Network request data processing

The default provides two types of data requests, one for Stringrequest and one for Jsonrequest

The jsonrequest is also divided into:

· jsonarrayrequest

Jsonarrayrequest request = new jsonarrayrequest ("url", new response.listener<jsonarray> () {@Overridepublic void Onresponse (Jsonarray response) {//Request response returned Jsonarray}}, New Response.errorlistener () {@Overridepublic void Onerrorresponse (Volleyerror error) {}}); Mrequestqueue.add (request);

· jsonobjectrequest

Jsonobjectrequest request = new Jsonobjectrequest (method.get, weather_json_address, NULL, new response.listener< Jsonobject> () {@Overridepublic void Onresponse (jsonobject response) {//The JSONObjectSystem.out.println returned by the request response ( Response);}},new Response.errorlistener () {@Overridepublic void Onerrorresponse (volleyerror error) { System.out.println ("Test4jsonobjectrequest-error");}); Mrequestqueue.add (Request);
Mrequestqueue.add (Request); Joins the request to the queue. There can be a lot of add queued operations, and then start
Mrequestqueue.start (); Start request
Mrequestqueue.stop (); Stop Request

Picture Load Request· Imagerequest Loading Pictures

Used in the same way as above jsonrequest

private void Requestbyimagerequest (final ImageView ImageView, String url) {imagerequest imgrequest = new Imagerequest (URL , new response.listener<bitmap> () {@Overridepublic void Onresponse (Bitmap Bitmap) {// After successful download imageview.setimagebitmap (bitmap),}, Imageview.getwidth (), Imageview.getheight (), config.rgb_565, new Errorlistener () {@Overridepublic void Onerrorresponse (volleyerror error) {//Download Error}}); Mrequestqueue.add (imgrequest); Mrequestqueue.start ();}

· Imageloader Loading Pictures

private void Requestbyimageloader (ImageView ImageView, String url) {int maxmemory = (int) runtime.getruntime (). maxmemory  ();//app maximum memory bytes int mcachesize = MAXMEMORY/8; Use 1/8 as the cache final lrucache<string, bitmap> mlruimagecache = new lrucache<string, bitmap> (mcachesize) {@ overrideprotected int sizeOf (String key, Bitmap value) {//Calculate memory for a picture Sizeif (Android.os.Build.VERSION.SDK_INT >= 12) { return Value.getbytecount (); Requires API >=12, total bytes} else {return value.getrowbytes () * value.getheight ();//per line byte multiplied by high (row) Api1}}};imagecache Imagecach E = new Imagecache () {@Overridepublic void Putbitmap (String key, Bitmap value) {mlruimagecache.put (key, value);} @Overridepublic Bitmap Getbitmap (String key) {return mlruimagecache.get (key);}};i Mageloader Mimageloader = new Imageloader (Mrequestqueue, Imagecache);// The second parameter of Imageloader.getimagelistener is the default picture resource ID, the requested picture is empty when set///The third parameter is the resource ID when the request fails, can be specified as 0ImageListener listener = Imageloader.getimagelistener (ImageView, Android. R.drawable.ic_menu_rOtate,android. R.drawable.ic_delete); Mimageloader.get (URL, listener); The Get method has started executing the load url-bitmap//imagecontainer imagecontainer = mimageloader.get (URL, listener); The Get method has started executing the load url-bitmap//bitmap bitmap = Imagecontainer.getbitmap ();//string Requesturl = Imagecontainer.getrequesturl ();}

Imageloader need to be constructed in conjunction with Imagecache. Imagecache is a interface

Imagecache Put/get Bitmap method, the recommended use of LRUCache to achieve.

Imagelistener is a interface, available in two ways: Onresponse (), Onresponseerror ()

Imageloader Picture loading process:imageloader.get (URL, listener), determine if it exists in the cache, and if so, take it out directly and display it in listener; A imagerequest, added to the Requestqueue, invokes the corresponding method in the listener in Response.listener in Imagerequest.


· networkimageview loading Pictures

private void Requestbynetworkimg (Networkimageview imageView, String URL) {Final lrucache<string, bitmap> Mimagecache = new lrucache<string, bitmap> (8*1024*1024) {@Overrideprotected int sizeOf (String key, Bitmap value) {/ /Calculate the memory of a picture Sizereturn value.getrowbytes () * Value.getheight (); Bytes per row multiplied by high (OK)   api1}};imagecache imagecache = new Imagecache () {@Overridepublic void Putbitmap (String key, Bitmap Value) {Mimagecache.put (key, value);} @Overridepublic Bitmap Getbitmap (String key) {return mimagecache.get (key);}};i Mageloader Mimageloader = new Imageloader (Mrequestqueue, Imagecache); */* SetUrl when the implementation is: with Imageloader, You can perform the operation of loading Url-bitmap */imageview.setdefaultimageresid (0); Default Figure Imageview.seterrorimageresid (0); Error figure Imageview.setimageurl (URL, mimageloader); }

This is a custom component that inherits from ImageView.

Imageview.setdefaultimageresid (0); Default diagram
Imageview.seterrorimageresid (0); Error map
Imageview.setimageurl (URL, mimageloader);

Combined with Imageloader, the internal call to Imageloader.get () is implemented to load the picture.

The item in the ListView uses Networkimageview:

Only a new Imageloader object is required. Different item,set different URLs can be.

Because in Imageloader, a different imagerequest is added to the requestqueue to perform the download.


Custom Request

/** * Volley adapter for JSON requests that'll be parsed into Java objects by Gson.    */public class Gsonobjectrequest<t> extends request<t> {protected final Gson Gson = new Gson ();    Protected final class<t> Clazz;    Protected final map<string, string> headers;    Protected final listener<t> Listener;     /** * Make a GET request and return a parsed an object from JSON.  * * @param URL of the URL of the request to make * @param clazz relevant class object, for Gson ' s reflection * @param Headers Map of Request headers */public gsonobjectrequest (int method, String URL, class<t> clazz, map<st Ring, string> headers, listener<t> Listener, Errorlistener Errorlistener) {Super (method, URL,        Errorlistener);        This.clazz = Clazz;        This.headers = headers;    This.listener = listener; } public gsonobjectrequest (String URL, class<t> clazz, map<string, string> headers, ListEner<t> Listener, Errorlistener Errorlistener) {This (Method.get, URL, clazz, headers, listener, errorlistener);  } @Override public map<string, String> getheaders () throws Authfailureerror {return headers! = NULL ?    Headers:super.getHeaders ();    } @Override protected void Deliverresponse (T response) {listener.onresponse (response); }//Convert the requested JSON into a corresponding object with Gson @Override protected response<t> parsenetworkresponse (Networkresponse R Esponse) {try {string json = new String (Response.data, Httpheaderparser.parsechars            ET (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)); }    }}
Custom request requires at least rewrite parsenetworkresponse () ,deliverresponse ()

Other Notes

The disk cache directory is defined in the volley class.

Request. Cancel () to cancel one of the requests.

Request. Settag (String tag), set a tag

Requestqueue. Cancelall (String tag), cancels the request for the same tag identity

Requestqueue. Cancelall (New Requestfilter () {}); Use Requestfilter to filter the request that needs to be canceled


Example : http://download.csdn.net/detail/jjwwmlp456/8176595


Android volley Google releases a library of tools for network communications

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.