Android Volley specifically explains Google's published set 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); Increase the queue for the request. Able to have very many add queued operations. Then start
Mrequestqueue.start (); Start request
Mrequestqueue.stop (); Stop Request

Picture Loading 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 to run loaded url-bitmap//imagecontainer Imagecontainer = mimageloader.get (URL, listener); The Get method has started to run loaded url-bitmap//bitmap bitmap = Imagecontainer.getbitmap ();//string Requesturl = Imagecontainer.getrequesturl ();}

Imageloader need to be constructed in conjunction with Imagecache.

Imagecache is a interface

Imagecache's method of Put/get bitmap. It is recommended to use LRUCache to implement.

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

Imageloader Picture loading process:imageloader.get (URL, listener), inferred if it exists in the cache. Suppose there is. is removed directly and displayed in the listener. If not, then a new imagerequest is added to the requestqueue. The corresponding method in listener is called in the 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. The implementation of the inside is: With the Imageloader, you can run the operation loaded into the Url-bitmap */imageview.setdefaultimageresid (0); Default Figure Imageview.seterrorimageresid (0); Error figure Imageview.setimageurl (URL, mimageloader); }

This is a self-defining component that inherits from ImageView.

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

Combining Imageloader, the internal call Imageloader.get () to implement the image loading.

The item in the ListView uses Networkimageview:

Just need a new Imageloader object. Different Item,set different URLs are available.

The download is run in Imageloader with new Imagerequest added to Requestqueue.


define the request yourself

/** * 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 the 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)); } }}

Define the request yourself. At least rewrite parsenetworkresponse () ,deliverresponse ()

Other Instructions

The disk cache folder is defined in the volley class.

Request. Cancel (), the ability to cancel a demand.

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


Demo sample : http://download.csdn.net/detail/jjwwmlp456/8176595


Android Volley specifically explains Google's published set of tools for network communications

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.