Volley, a good helper for small concurrent network requests

Source: Internet
Author: User

Have to say, when do not understand one thing, it will be like, of course, it is very mysterious. But when it comes to the mysterious item, it doesn't feel that way. As a novice Android developer, I have just contacted volley this open-source network request framework, it was instantly touched by her. I'll talk about some of my understanding of volley.

What is volley?

Volley is Google in the 2013 I/O Conference on the framework of a network request, volley in the performance of the large-scale adjustment, its design goal is very suitable for the data volume is not small, but the traffic is frequent network operation, and for large data volume of network operations, such as downloading files, etc., Volley's performance will be very bad. its model.

How to use Volley?

Speaking of the use of volley, we need to first understand the framework of the implementation of the business process, as follows:

Then it's about learning about several commonly used classes in the API and how to use them.

  • Volley:volley externally exposed APIs, new and started a request queue Requestqueue through the Newrequestqueue (...) function.
  • Request: Represents an abstract class of requests. Stringrequest, Jsonrequest, and Imagerequest are all its subclasses, representing some kind of request.
  • Requestqueue: Represents the request queue, which contains a cachedispatcher (for processing the scheduler thread that walks the cache request), an Networkdispatcher array (the dispatch thread used to handle the network request), A responsedelivery (returns the result distribution interface), starting with the start () function, starts Cachedispatcher and networkdispatchers.
    Cachedispatcher: A thread that is used to schedule requests to process the walk cache. After startup, the request processing is continuously taken from the cache request queue, the queue is empty, and the request processing ends, and the result is passed to the responsedelivery for subsequent processing. When the result is not cached, the cache is invalidated, or the cache needs to be refreshed, the request needs to be re-networkdispatcher to dispatch processing.
  • Networkdispatcher: A thread that is used to schedule requests to process a network. After starting, the request processing is continuously taken from the network request queue, the queue is empty, the request processing is finished, the result is passed to Responsedelivery to perform subsequent processing, and the results are determined to be cached.
  • Responsedelivery: Returns the result distribution interface, which is currently only distributed within the corresponding thread of the Executordelivery handler based on the.
  • Httpstack: Processes the Http request and returns the result of the request. Currently, there are httpurlconnection-based Hurlstack and httpclientstack based on Apache HttpClient in volley.
  • Network: Call Httpstack to process the request and convert the result to a networkresponse that can be responsedelivery processed.
    Cache: Cached request results, volley by default using SDcard-based
  • Diskbasedcache. Networkdispatcher The result of the request and determines whether it needs to be stored in Cache,cachedispatcher will cache the results from the caches.

Okay, well, we know all about it, and here's a little example of the actual experience.

A small example of my volley

What I want to accomplish is to click on a button and then display a picture on the two imageview below. So, let's get started.
The first thing we need to do is to import the required Volley.jar package in the Libs directory of our new project. And then import it classpath.
Then is the design layout, perfect business logic code. Take a look at the detailed explanations below.

The first is the layout file:

<relativelayout 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: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=". Mainactivity "> <button android:id="@+id/btn_getimage"Android:layout_width="Wrap_content"android:layout_height="Wrap_content"android:layout_alignparentleft="true"android:layout_alignparentright="true"android:layout_alignparenttop="true"android:layout_margintop="24DP"android:onclick="Setimageto"android:text="GetImage"/> <imageview android:id="@+Id/imageview"Android:layout_width="Wrap_content"android:layout_height="Wrap_content"android:layout_below="@id/btn_getimage"Android:layout_centerinparent="true"android:layout_margintop="7DP"android:visibility="Invisible"Android:src="@drawable/ic_launcher"/> <com.android.volley.toolbox.networkimageview android:id="@+Id/network_image_view"Android:layout_width="Wrap_content"android:layout_height="Wrap_content"android:layout_below="@id/imageview"Android:layout_centerinparent="true"android:layout_gravity="Center_horizontal"Android:src="@drawable/error"/> </relativelayout>

Then the Java code:

 PackageCom.guoribiao.volleytest;Importandroid.app.Activity;ImportAndroid.graphics.Bitmap;ImportAndroid.os.Bundle;ImportAndroid.support.v4.util.LruCache;ImportAndroid.view.Menu;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.ImageView;ImportCom.android.volley.RequestQueue;ImportCom.android.volley.toolbox.ImageLoader;ImportCom.android.volley.toolbox.ImageLoader.ImageCache;ImportCom.android.volley.toolbox.ImageLoader.ImageListener;ImportCom.android.volley.toolbox.NetworkImageView;ImportCom.android.volley.toolbox.Volley; Public  class mainactivity extends Activity {    PrivateButton Mbutton;PrivateImageView Mimageview;PrivateNetworkimageview Networkimageview; Public void Initview() {Mbutton = (Button) Findviewbyid (r.id.btn_getimage);        Mimageview = (ImageView) Findviewbyid (R.id.imageview);    Networkimageview = (Networkimageview) Findviewbyid (R.id.network_image_view); }@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main);    Initview (); } Public void Setimageto(View view)        {setimage ();    Setimagebynetworkimageview (); }/** * Use a network picture control that comes with volley to load the network picture * /    Private void Setimagebynetworkimageview() {//Set the URL address of the picture for the network requestString Requesturl ="https://ss0.bdstatic.com/94ojfd_baact8t7mm9gukt-xh_/timg?image&quality=100&size=b4000_4000& sec=1461212709&di=978a557d108c531a9f76f225454d0c5b&src=http://img5.duitang.com/uploads/item/201509/10/ 20150910195025_uaszx.jpeg ";//Create a request queueRequestqueue queue = Volley.newrequestqueue ( This);//cache picture using caching mechanism        Finallrucache<string, bitmap> LruCache =NewLrucache<string, Bitmap> ( -);//Use the LRUCache above to implement the Imagecache settingsImagecache Imagecache =NewImagecache () {@Override             PublicBitmapGetbitmap(String URL) {lrucache.get (URL);return NULL; }@Override             Public void Putbitmap(String URL, Bitmap Bitmap)            {lrucache.put (URL, bitmap); }        };//Create a picture loaderImageloader Imageloader =NewImageloader (Queue,imagecache);//Set the label for the controlNetworkimageview.settag ("url");//Set the URL and picture loader for the picture that will be displayedNetworkimageview.setimageurl (Requesturl, Imageloader); }/** * Load a picture on the network with volley on a ImageView control */    Private void setimage() {//Set the ImageView to a visible stateMimageview.setvisibility (1);//Set up a request queueRequestqueue queue = Volley.newrequestqueue ( This);//Set the address of the URL where the picture is locatedString IMAGEURL ="Http://www.baidu.com/img/bd_logo1.png";//Set a LRUCache        Finallrucache< String, Bitmap > Cache =NewLrucache<string, Bitmap> ( -);//Generate a picture bufferImagecache Imagecache =NewImagecache () {@Override             PublicBitmapGetbitmap(String URL) {cache.get (URL);return NULL; }@Override             Public void Putbitmap(String URL, Bitmap Bitmap)            {cache.put (URL, bitmap); }        };//Initialize a picture loaderImageloader Imageloader =NewImageloader (Queue,imagecache);//Set a listener in the picture loading process and add it to the control to be displayedImagelistener listener = Imageloader.getimagelistener (Mimageview, R.drawable.ic_launcher, R.drawable.error);//Set the loaded URL address and listenerImageloader.get (IMAGEURL, listener); }}

Finally, don't forget to declare the network permissions in the manifest.xml manifest file.

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

Let's take a look at the results of the test.


And, when we just clicked on the button, we found that the ImageView control above shows a default Ic_launcher icon. This is because it is just loading. When the load is complete, a normal network image is displayed.

Summarize

The use of volley words, suitable for those small traffic, the number of requests frequent network requests, not suitable for big data download, so we need to follow their own needs to choose to use.

Direction of improvement:
Others, although useful, but is not the most suitable for their own. On the basis of volley, we can create our own network Request resource code base, for example, the special needs of the network request for two times encapsulation, so as to save a lot of time to write repetitive code. can also be effectively processed. Why not.

Volley, a good helper for small concurrent network requests

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.