Use of Android Volley library

Source: Internet
Author: User

Content of this article
    • What is the Volley library
    • What can volley do?
    • Volley architecture
    • Demonstrating the use of the volley library
    • Resources

Android about network operation generally will introduce HttpClient and httpconnection these two packages. The former is the Apache Open Source Library, the latter is the Android comes with the API. For enterprise applications, you will typically choose to use an already encapsulated HTTP framework. More popular are volley, android-async-http, retrofit, Okhttp, Androidquery, Androidasync and so on. They have different characteristics, different frameworks have various efficiency, now Google launched the official Internet Communication Library for Android platform volley, can make network communication faster, simpler, more robust, volley in providing high-performance network communication capabilities, while It also provides good support for network picture loading, which can meet the needs of the simple REST client completely. In addition, volley is highly scalable and can customize your own network requests as needed.

What is the Volley library

Volley is a library of processing and caching network requests released by Ficus kirpatrick in Gooogle I/O 2013, making network communication faster, simpler, and more robust. The origin of the volley name is a burst or emission of many things or a large amount at once. In the Gooogle I/O 2013 speech, the picture is a fire bow. As shown in 1.

Figure 1 Gooogle I/O volley

Volley manages the processing and caching of network requests, saving developers valuable time and writing the same network call/cache code over and over again. One of the benefits of less repeating code is that it reduces bugs, which is what all developers expect.

The so-called "write the same network call/cache code again and again" is asynctask and the logic/code you write to get the response through the Web API and display it. We must take care of progressbar/progressdialog within the ProgressBar () and OnPostExecute () methods. Although this is not a daunting task, it is boring and even tiring, although I have defined the Basetask class to manage the display/cancellation of progressbar/progressdialog and more. Now, volley is a powerful tool for replacing Asynctask.

What can volley do?

The volley is suitable for small and fast data transmission, especially for the following two scenarios:

    • JSON Object
    • Picture loading

Volley Advantages:

  1. Volley can automatically schedule all network requests. This means that volley will take care of all network requests that your APP takes to get a response or picture from the Web.
  2. The volley provides transparent disk and memory caching.
  3. The volley provides a powerful cancellation request API. This means that you can cancel a separate request, or you can set the block of the cancellation request (can be multiple) or range.
  4. The volley offers powerful customization capabilities.
  5. Volley provides debugging and tracing tools.

Volley architecture

Volley uses the line pool as the infrastructure, mainly divided into the main thread, the cache thread and the network thread. Both the main thread and the cache thread have only one, and the networkdispatcher thread can have multiple, which solves the problem of parallelism.

Figure 2 Volley architecture

Demonstrating the use of the volley library

Download the demo, import the volley library and presentation project into Eclipse, and add the volley library to the demo project. The program runs as shown in result 3, which contains two demos: The network gets JSON and pictures.

Figure 3 Left: program main interface; Middle: click "Get JSON"; Right: click "Get Image"

The main program Activity_main.xml interface contains two buttons that show the activity of two demos, the core code is as follows:

 Public class Mainactivity extends Activity {
    null;
    @Override
    protected void onCreate (Bundle savedinstancestate) {
        Super.oncreate (savedinstancestate);
        Setcontentview (R.layout.activity_main);
        Findviewbyid (R.id.btn_json). Setonclicklistener (
                New View.onclicklistener () {
                    @Override
                     Public void OnClick (View v) {
                        New Intent (mainactivity.  this, Jsondemo. class);
                        StartActivity (Intent);
                    }
                });
        Findviewbyid (r.id.btn_img). Setonclicklistener (
                New View.onclicklistener () {
                    @Override
                     Public void OnClick (View v) {
                        New Intent (mainactivity.  this, Imgdemo. class);
                        StartActivity (Intent);
                    }
                });
    }
}
Get JSON

Get weather conditions in Beijing by accessing the JSON interface provided by the National weather volley.

    • Http://www.weather.com.cn/data/sk/101010100.html
      Http://www.weather.com.cn/data/cityinfo/101010100.html
      Http://m.weather.com.cn/data/101010100.html
      Among them,101010100 represents Beijing.

The Activity_json.xml page file contains a TextView control and a Progreebar control, and the core code is as follows:

Package com.example.volleyexample;
Import android.app.Activity;
Import Org.json.JSONObject;
Import Com.android.volley.Request;
Import Com.android.volley.RequestQueue;
Import Com.android.volley.Response;
Import Com.android.volley.VolleyError;
Import Com.android.volley.toolbox.JsonObjectRequest;
Import Com.android.volley.toolbox.Volley;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.TextView;
 Public class Jsondemo extends Activity {
    Private TextView Txtdisplay;
    @Override
    protected void onCreate (Bundle savedinstancestate) {
        Super.oncreate (savedinstancestate);
        Setcontentview (R.layout.activity_json);
        Txtdisplay = (TextView) Findviewbyid (R.id.txtdisplay);
        Requestqueue queue = Volley.newrequestqueue (this);
        "http://www.weather.com.cn/data/sk/101010100.html";
        New Jsonobjectrequest (
                null,
                New Response.listener<jsonobject> () {
                    @Override
                     Public void Onresponse (jsonobject response) {
                        TODO auto-generated Method Stub
                        Txtdisplay.settext ("Response = +" + response.tostring ());
                        Findviewbyid (R.ID.PROGRESSBAR1)
                                . setvisibility (View.gone);
                    }
                New Response.errorlistener () {
                    @Override
                     Public void onerrorresponse (volleyerror error) {
                        TODO auto-generated Method Stub
                    }
                });
        Queue.add (jsobjrequest);
    }
}
Get image

The Activity_img.xml page file contains two controls:ImageView and Networkimageview, wherenetworkimageview is volley The provided controls, after all, load the picture with a high frequency, slightly, the core code is as follows:

Package com.example.volleyexample;
Import Org.json.JSONObject;
Import Com.android.volley.Request;
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.NetworkImageView;
Import Com.android.volley.toolbox.Volley;
Import android.app.Activity;
Import Android.graphics.Bitmap;
Import Android.os.Bundle;
Import Android.support.v4.util.LruCache;
Import Android.widget.ImageView;
 Public class Imgdemo extends Activity {
    "Http://images.cnblogs.com/cnblogs_com/liuning8023/588559/o_Android.jpg";
    protected void onCreate (Bundle savedinstancestate) {
        Super.oncreate (savedinstancestate);
        Setcontentview (R.LAYOUT.ACTIVITY_IMG);
        Requestqueue mrequestqueue = Volley.newrequestqueue (this);
        New Lrucache<string, Bitmap> (
                20);
        New Imagecache () {
            @Override
             Public void value) {
                value);
            }
            @Override
             Public Bitmap Getbitmap (String key) {
                return mimagecache.get (key);
            }
        };
        New Imageloader (Mrequestqueue, Imagecache);
        ImageView
        ImageView img = (ImageView) Findviewbyid (R.id.imgview);
        Imagelistener listener = Imageloader
                . Getimagelistener (IMG, Android. R.drawable.ic_menu_rotate,
                        Android. R.drawable.ic_delete);
        Mimageloader.get (URL, listener);
        Networkimageview
        Networkimageview Netimgview = (networkimageview) Findviewbyid (R.id.networkimgview);
        Netimgview.settag ("url");
        Netimgview.setimageurl (URL, mimageloader);
    }
}

Resources
    • Android Async HTTP Clients:volley vs Retrofit
    • Android Volley
    • Android Volley Examples

Download Demo

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.