Android network communication Framework Volley introduction

Source: Internet
Author: User

Volley, which was released on Google I/O in 2013, is a network communication library on the Android platform that encapsulates commonly used network communications to make network communication faster, simpler, and more robust. Previously used network communication is generally used Asynctaskloader, httpurlconnection, Asynctask and so on.

Volley for small amounts of data but frequent communication

Volley architecture

Is the image that Google I I am using when I am speaking


The main thread, cache thread, network thread, it can be seen that the main thread, the cache thread has only one, and the networkdispatcher thread can have multiple, the entire schema is based on the thread pool. Volley's main role:
1. Get the JSON object
2. Image loading

Benefits of using Volley:
1, Volley automatically schedule all network requests. It means that volley'll be taking care of the network requests your app executes for fetching response or image from Web.
2, volley provides transparent disk and memory caching.
3, Volley provides powerful cancellation request API. It means that can cancel a single request or you can set blocks or scopes of requests to cancel.
4, Volley provides powerful customization abilities.
5. Volley provides debugging and tracing tools
Use of volley
The first thing to get volley source or jar package
git address for volley: Https://android.googlesource.com/platform/frameworks/volley
After installing Git, you can get its source code with the following command:

git clone Https://android.googlesource.com/platform/frameworks/volley
Use the following command on the Ubuntu12.04 terminal to get the latest volley source code, and then compile the jar package in the source environment.

[Email protected]:~/volley$ git clone https://android.googlesource.com/platform/frameworks/volleyCloning into ' Volley ' ... remote:counting objects:52, doneremote:finding sources:100% (52/52) remote:total 2851 (Delta 259), reused 28 Wuyi (Delta 259) receiving objects:100% (2851/2851), 1.13 MiB | 369 kib/s, done. Resolving deltas:100% (259/259), done.
Compiling the volley module with source code

[Email protected]:~/dzt/android_source_4.4$ mmm/home/dzt/gioneeapp/volley/volley/========================= ===================platform_version_codename=relplatform_version=4.4.2target_product=aosp_armtarget_build_ Variant=engtarget_build_type=releasetarget_build_apps=target_arch=armtarget_arch_variant=armv7-atarget_cpu_ variant=generichost_arch=x86host_os=linuxhost_os_extra=linux-3.11.0-26-generic-x86_64- with-ubuntu-12.04-precisehost_build_type=releasebuild_id=kot49hout_dir=out==================================== ========make: Enter directory '/home/dzt/dzt/android_source_4.4 ' target Java:volley (out/target/common/obj/java_libraries/ volley_intermediates/classes) Note:/home/dzt/gioneeapp/volley/volley/src/main/java/com/android/volley/ The Requestqueue.java uses an unchecked or unsafe operation. Note: To learn more, recompile with-xlint:unchecked. copying:out/target/common/obj/java_libraries/volley_intermediates/classes-jarjar.jarcopying:out/target/common/ Obj/java_libraries/volley_intermediates/emma_out/lib/classes-jarjar.jarcopying:out/targeT/common/obj/java_libraries/volley_intermediates/classes.jartarget Static Jar:volley (out/target/common/obj/JAVA_ Libraries/volley_intermediates/javalib.jar) Make: Leave the directory "/home/dzt/dzt/android_source_4.4" [email protected]:~  /dzt/android_source_4.4$
Generates a static jar package, path: Out/target/common/obj/java_libraries/volley_intermediates/javalib.jar

Volley source and jar package can be downloaded here: http://download.csdn.net/detail/deng0zhaotai/8581201

Simple application of Volley


Print JSON data

04-10 15:50:54.932 D/volley_dzt (6005): jsonrequest------POST------{"Weatherinfo": {"Weather6": "Drizzle to Yin", "weather5": " Light Rain "," weather4 ":" Yin Turn Light Rain "," Index_d ":" Recommended thin jacket, cardigan denim shirt pants and other clothing. " The frail and infirm should be suitably added clothing, suitable for jackets, thin sweaters and so on. "City": "Shenzhen", "Img_single": "1", "INDEX_CL": "Suitable", "IMG2": "The", "IMG1": "1", "index": "More Comfortable", "tempF1": "68℉~59℉", "Img_ Title10 ":" Light Rain "," Img_title11 ":" Light Rain "," img_title12 ":" Yin "," index_xc ":" Not Appropriate "," Index_co ":" Comfortable "," img_title_single ":" Cloudy "," Date_y ":" March 4, 2014 "," city_en ":" Shenzhen "," Index48_d ":" Recommended thin jacket, cardigan denim shirt pants and other clothing. The frail and infirm should be suitably added clothing, suitable for jackets, thin sweaters and so on. "," Img9 ":" 7 "," Img7 ":" 2 "," Img8 ":" 7 "," Img5 ":" 7 "," Img6 ":" "," IMG3 ":" 7 "," IMG4 ":" The Wind "," FX1 ":" The Breeze "," st5 ":" "," St6 ":" "," "ST3": "+", "date": "," St4 ":" "," "St1": "", "" St2 ":" "," "Temp1": "20℃~15℃", "tempF6": "66.2℉~57.2℉", "Temp2": " 20℃~15℃ "," Temp3 ":" 21℃~16℃ "," index48 ":" More Comfortable "," tempF4 ":" 66.2℉~60.8℉ "," tempF5 ":" 68℉~59℉ "," Index_ls ":" Suitable "," tempF2 ": "68℉~59℉", "tempF3": "69.8℉~60.8℉", "index_tr": "Suitable", "Index_ag": "Very easy to send", "INDEX48_UV": "Weakest", "fl1": "Less than 3 levels", "FL5": "Less than 3 levels", "Fl4": "Less than 3 levels", "TEMP6": "19℃~14℃", "Fl3": "3-4 Levels", "TEMP5": "20℃~15℃", "FL2 ":" Less than Level 3 "," Temp4 ":" 19℃~16℃ "," Cityid ":" 101280601 "," Img_title7 ":" Yin "," img12 ":" 2 "," Img_title6 ":" Drizzle "," fl6 ":" Less than 3 levels ", "Img_title5": "Light Rain", "img_title4": "Light Rain", "Fchh": "One", "img_title9": "Light Rain", "img10": "", "Img_title8": "Light Rain", "img11": "7", " FX2 ":" Breeze "," wind1 ":" Breeze "," weather1 ":" Cloudy "," Wind3 ":" Dongfeng 3-4 "," Weather2 ":" Light Rain "," Wind2 ":" Breeze "," weather3 ":" Drizzle "," Wind5 ":" Breeze "," img_title3 ":" Light Rain "," Index_uv ":" Weak "," Wind4 ":" Breeze "," img_title2 ":" Cloudy "," Img_title1 ":" Cloudy "," Wind6 ":" Breeze "," Week ":" Tuesday "}}
Reference Code

Package Com.dzt.volleydemo;import Java.util.hashmap;import Java.util.map;import org.json.jsonobject;import Android.app.progressdialog;import Android.graphics.bitmap;import Android.os.bundle;import Android.support.v4.util.lrucache;import Android.support.v7.app.actionbaractivity;import Android.util.Log;import Android.widget.imageview;import Com.android.volley.authfailureerror;import Com.android.volley.Request.Method; Import Com.android.volley.requestqueue;import Com.android.volley.response;import com.android.volley.VolleyError; Import Com.android.volley.toolbox.imageloader;import Com.android.volley.toolbox.imageloader.imagecache;import Com.android.volley.toolbox.imageloader.imagelistener;import Com.android.volley.toolbox.jsonobjectrequest;import Com.android.volley.toolbox.networkimageview;import Com.android.volley.toolbox.stringrequest;import Com.android.volley.toolbox.volley;public class Mainactivity extends Actionbaractivity {private static final String TAG = "Volley_dzt";p rivate staticFinal string URL = "http://www.baidu.com";p rivate static final String weather_url = "http://m.weather.com.cn/data/ 101280601.html ";p rivate static final String PICTURE1 =" Http://img05.tooopen.com/images/20150407/tooopen_sy_ 84397424841.jpg ";p rivate static final String PICTURE2 =" Http://img1.3lian.com/img2008/06/019/cn32.jpg ";p rivate Requestqueue mqueue;private ImageView mimageview;private networkimageview mnetworkimageview; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Mqueue = Volley.newrequestqueue (Getapplicationcontext ()); Requestget (); LOG.I (TAG, "---------------------------------------------------1"); Requestpost (); LOG.I (TAG, "---------------------------------------------------2"); Jsonrequest (); Getjsonrequest ();p ostjsonrequest (); LOG.I (TAG, "---------------------------------------------------3"); Initwidget (); Loadimagebyvolley (); Showimagebynetworkimageview ();} private void Initwidget () {Mimageview = (ImageView) Findviewbyid (r.id.imageview); Mnetworkimageview = (Networkimageview) Findviewbyid (R.id.networkimageview) ;} /** * Use Networkimageview to display network pictures */private void Showimagebynetworkimageview () {final lrucache<string, bitmap> LruCache = new lrucache<string, bitmap>, Imagecache imagecache = new Imagecache () {@Overridepublic void Putbitma P (String key, Bitmap value) {log.i (TAG, "Showimagebynetworkimageview-------------------Putbitmap"); Lrucache.put (key , value);} @Overridepublic Bitmap Getbitmap (String key) {log.i (TAG, "Showimagebynetworkimageview-------------------Getbitmap") ; return Lrucache.get (key);}};i Mageloader Imageloader = new Imageloader (Mqueue, Imagecache); Mnetworkimageview.settag ("url"); Mnetworkimageview.setimageurl (PICTURE1, imageloader);} /** * Loading images asynchronously with volley * */private void Loadimagebyvolley () {final lrucache<string, bitmap> LruCache = new LRUCACHE&L T String, bitmap>, Imagecache imagecache = new Imagecache () {@Overridepublic void Putbitmap (string key, BiTMap value) {log.i (TAG, "Loadimagebyvolley-------------------Putbitmap"); Lrucache.put (key, value);} @Overridepublic Bitmap Getbitmap (String key) {log.i (TAG, "Loadimagebyvolley-------------------Getbitmap"); return Lrucache.get (key);}};i Mageloader Imageloader = new Imageloader (Mqueue, Imagecache);//Note Getimagelistener parameter Imagelistener listener = Imageloader.getimagelistener (Mimageview,r.drawable.ic_launcher, R.drawable.error); ImageLoader.get (PICTURE2, listener);} private void Requestget () {stringrequest stringrequest = new Stringrequest (url,new response.listener<string> () {@ overridepublic void Onresponse (String response) {LOG.D (TAG, "requestget----------" + response);}}, New Response.errorlistener () {@Overridepublic void Onerrorresponse (volleyerror error) {LOG.E (TAG, Error.getmessage (), (error);}}); Mqueue.add (stringrequest);} private void Requestpost () {stringrequest stringrequest = new Stringrequest (method.post, Url,new response.listener< String> () {@Overridepublic void Onresponse (String response) {LOG.D (TAG, "requestpost----------" + response);}, new Response.errorlistener () {@Overridepublic void Onerrorresponse (volleyerror error) {LOG.E (TAG, Error.getmessage (), error);}}) {@Overrideprotected map<string, string> getparams () throws Authfailureerror {//TODO auto-generated method Stubmap <string, string> map = new hashmap<string, string> (), Map.put ("Params1", "value1"), Map.put ("Params2", " Value2 "); return map;}; Mqueue.add (stringrequest);} /** * Use volley to get JSON data */private void Jsonrequest () {//Show progress bar final ProgressDialog progressdialog = progressdialog.show (th IS, "This is the title", "... Loading ... "); Jsonobjectrequest jsonobjectrequest = new Jsonobjectrequest (Weather_url, NULL, new Response.listener<jsonobject > () {@Overridepublic void Onresponse (jsonobject response) {LOG.D (TAG, "jsonrequest------------" + response.tostring ());//Cancel the progress bar if (progressdialog.isshowing () && progressdialog! = null) {Progressdialog.dismiss ()}}, new Response.errOrlistener () {@Overridepublic void Onerrorresponse (volleyerror error) {LOG.E (TAG, Error.getmessage (), error);}}); Mqueue.add (jsonobjectrequest);} /** * Get JSON data with volley GET request */private void Getjsonrequest () {jsonobjectrequest jsonobjectrequest = new Jsonobjectrequest (Method.get,weather_url, NULL, new Response.listener<jsonobject> () {@Overridepublic void Onresponse (jsonobject Response) {LOG.D (TAG, "jsonrequest-----GET-------" + response.tostring ())}, new Response.errorlistener () {@ overridepublic void Onerrorresponse (volleyerror error) {LOG.E (TAG, Error.getmessage (), error);}}); Mqueue.add (jsonobjectrequest);} /** * Get JSON data using volley POST request */private void Postjsonrequest () {jsonobjectrequest jsonobjectrequest = new Jsonobjectreque St (Method.post, Weather_url, Null,new response.listener<jsonobject> () {@Overridepublic void Onresponse ( Jsonobject response) {LOG.D (TAG, "jsonrequest------POST------" + response.tostring ());}, New Response.errorlistener ( ) {@Overridepublic void OnerrorresponSE (volleyerror error) {LOG.E (TAG, Error.getmessage (), error);}}); Mqueue.add (Jsonobjectrequest);}}
Layout file

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "vertical" android:paddingbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_ Horizontal_margin "android:paddingright=" @dimen/activity_horizontal_margin "android:paddingtop=" @dimen/activity_ Vertical_margin "tools:context=" com.dzt.volleydemo.MainActivity "> < Com.android.volley.toolbox.NetworkImageView android:id= "@+id/networkimageview" android:layout_width= "match_p    Arent "android:layout_height=" 0DP "android:layout_margintop=" 10DP "android:layout_weight=" 1 "/> <imageview android:id= "@+id/imageview" android:layout_width= "Match_parent" android:layout_height= "0DP" android:layout_weight= "1"/></linearlayout>

Demo Program: http://download.csdn.net/detail/deng0zhaotai/8581755

There's also a way to get a picture

private void Requestimage () {imagerequest imgrequest = new Imagerequest (picture1,new response.listener<bitmap> () {@Overridepublic void Onresponse (Bitmap arg0) {//TODO auto-generated method Stubmsingleview.setimagebitmap (arg0);}}, config.argb_8888, New Errorlistener () {@Overridepublic void Onerrorresponse (Volleyerror arg0) {//TODO Auto-gen erated method stub}}); Mqueue.add (imgrequest);}
You can also cancel a request

@Overrideprotected void OnStop () {//TODO auto-generated method Stubsuper.onstop (); Mqueue.cancelall (this);}
Latest Download: http://download.csdn.net/detail/deng0zhaotai/8582101

Android network communication Framework Volley introduction

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.