Volle Introduction 02

Source: Internet
Author: User
Tags call back

----------------------------------------------------------------------------

Reprint: http://blog.csdn.net/crazy__chen/article/details/46483329

----------------------------------------------------------------------------

Volley is a Google-launched Android asynchronous network request framework and picture loading framework, especially for small data volume, frequent communication network operations.

You can download the source code at this address https://android.googlesource.com/platform/frameworks/volley/

Main features of Volley

(1). Strong extensibility. Most of the volley are based on the interface design, which is highly configurable.
(2). To a certain extent in line with the HTTP specification, including the return Responsecode (2xx, 3xx, 4xx, 5xx) processing, request header processing, caching mechanism support. and supports retry and priority definitions.
(3). Default Android2.3 and above based on the HttpClient implementation httpurlconnection,2.3
(4). Provides a simple image loading tool.

This column mainly through the analysis of the source code of the volley, the entire structure of its analyses, pointed out that it is such a design architecture, corresponding to the advantages of extensibility, coupling and so on. At the same time, it is pointed out that volley for the network request, considering the details, to guide us to write our own network framework in the future needs. In addition, according to the design of volley, the application of the scene, the volley face of the shortcomings, and how it can be more fully expanded.

This article as the beginning of the column, will give a simple introduction to the use of volley and volley the entire architecture design, through the introduction of the architecture, I hope you have a general impression of the implementation of the volley model. In this article, you do not have to pay attention to the implementation of the details (because in the next article will be introduced in detail), the main thing is to understand the volley design ideas, focus on the overall realization.

Online introduction Volley How to use a lot of articles, you can search for yourself, here I give a simple example of how to use the Volley network request.

Stringrequest stringrequest = new Stringrequest ("Http://www.baidu.com",      new Response.listener<string> () {          @Override public          void Onresponse (String response) {              //processing response          }      }, new Response.errorlistener () {          @Override public              void Onerrorresponse (volleyerror error) {                 //handling Errors          }      });  

  

With the code above we can see that we instantiate a Stringrequest object with a network address of www.baidu.com, two listeners

Observe the method inside the listener, one parameter is string response, one is Volleyerror error

In the literal sense, we create a request for the network requests, the address of the incoming request, after the successful request, will call back two listener methods, two listeners corresponding to the request successfully and the request failed.

OK, is not as long as this has opened the thread to request data. Not so simple, we also want to:

Requestqueue Mqueue = volley.newrequestqueue (context); Create request queue  Mqueue.add (stringrequest);//Add requests to the request queue  

  

The above operation adds the request we constructed to a new request queue. So far, we have made a successful request, and after the request is over, we will call back the method inside of requests.

This is the simplest use of volley.

Someone would ask, why join the request in the queue, I directly new a request, and then within the request to create a thread, request data, the last callback interface is not good?

It is not wrong to think so, but volley this design must have its own reasons, on the coupling too tight this point, we can know that the strategy we proposed above is not so elegant (does not mean that the non-line).

So how did volley do it? Let's take a look at the overall architecture diagram of volley (the figure from http://codekk.com/open-source-project-analysis/detail/Android/grumoon/Volley%20%E6%BA% 90%E7%A0%81%E8%A7%A3%E6%9E%90, if not allowed to reprint, please contact me)

The above figure is a little complicated, let's not tangle, we first see our previous conclusion, the use of volley process is

1, create request

2, put the request into the queue Requestqueue

3, Handling callback results

Note the example used in the stringrequest, corresponding to the diagram above, find request and stringrequest can know, Stringrequest is a subclass of request, literally can know, this is a string request, There are also json,image requests, all of which are the subclasses of request, so we assume that is not a different request, there is a different class?

It is this, from an object-oriented point of view, that we think of the request as a class, so every time we have a network request, only the new class will be added to the queue.

So how does the queue request data for me? Here I would like to introduce you to the mystery, as long as you understand the process can be, do not delve into the details.

In fact, there are two queues in Requestqueue, one I call cache queue Mcachequeue, one called network queue Mnetworkqueue

If a request is requested to join a cache queue (for example, we set a property shouldcache to request and then provide a set method), it will attempt to fetch the data from the hard disk cache, and if there is no cache, the request will be put into the network queue

If the request does not require caching, join the network queue directly.

After joining the queue, we open the thread and pull the request out of the queue.

It is conceivable that we should have a thread cachedispatcher from the cache queue, a networkdispatcher from the network queue, but the network request is often large, so volley actually have multiple threads from the network queue to take out the request ( This involves thread synchronization, volley using Priorityblockingqueue resolution)

Why create several threads to take from the queue instead of each request to open a thread? The benefit of this is to avoid the overhead of duplicating a large number of thread creation, and because all of the request is in a requestqueue to facilitate our management of the request, for example, we want to close a request, Or we ask for a lot of the same request, and for these operations, if we scatter requests, it is difficult to resolve them uniformly, so we can manage threads uniformly using the idea of a thread pool.

At the same time, this can be detrimental because the number of threads in the actual request thread is fixed, which means that when the number of requests is greater than the number of threads, some threads will be blocked, resulting in efficiency degradation, and more problems will be mentioned in the next article.

How do cachedispatcher and Networkdispatcher request data?

For Networkdispatcher, it is necessary to open the network connection, and then get the data (for example, Url.openconnection), which is our common implementation, do not do a detailed explanation (volley to these implementations in more detail encapsulation)

Think again, after we get the results, how do we call back.

Or an object-oriented approach, volley encapsulates the response result into a repsonse class (corresponding to the request)

For Networkdispatcher, in its run () method, after the request is obtained, the data is encapsulated into a Respsonse object according to the URL. There is one more dispatcher responsedelivery distributed to the corresponding request

Someone will ask? After parsing to response, we design a method for request (for example, Parserespose (Respsonse respsonse) to use response, and in this method, the callback listener is not good? Why do you want to superfluous and create a dispenser?

The reason is that this is more flexible, but there is also an important reason to notice that our callbacks are often done in the main thread (because it is very likely to operate the UI), if we are in Networkdispatcher (child thread), the direct callback, can cause errors, This is another reason for the existence of Responsedelivery.

Based on the above conclusions, let's take a look at a simple flowchart

Based on the process analysis, we can realize that the basic idea of the volley design framework, compared to our simple implementation, the implementation of volley is more loosely coupled, using interface-oriented programming, while using more combinations rather than inheritance. The use of design patterns such as proxies, while increasing the utilization of threads. In short, volley's architectural design also has various benefits.

I'm here to introduce a few volley features, as well as what it takes into consideration, and we probably don't have a problem to consider. These questions or functional advantages will be accompanied by this column in-depth let us gradually realize.

Here is a general introduction, you can compare your own ideas to see if you have any consideration (if you achieve such a framework)

1,request design, after we get response, we may want to have different forms of data (such as String,bitmap,jsonobject) based on project requirements, volley use abstract programming, Let's inherit the request to implement our own parsing of the response (meaning to handle the Stringrequest class provided by volley, etc., we customize the request)

2, retry policy, network requests may fail due to network reasons (such as cell phone disconnected), volley provides us with a retry policy

3, terminate the request, such as requesting data in the en route, we want to terminate the request

4,request in queue priority issues, such as our request is more urgent, should be ranked in front of the queue

5, the problem of repeated requests, the use of multiple identical requests in the queue, request to one, the other may not have to request, directly from the cache to take

6, exception handling, such as io,403,402 and other authorization errors

7, Address redirection processing

8, the processing of network problems, for example, we broke the network, volley used the network class to deal with this kind of problem

9, using HttpClient or url.openconnection () to request data?

10, cache read and store, we request to network data, can be stored in the local cache

11, how to set the request log to record the request information for debugging?

12, optimized for cache write and read efficiency

13, processing of picture requests

Now let's try Sledgehammer, first look at volley this class, volley as the entire framework of the entrance, in fact, is to create a requestqueue queue

public class Volley {/** * Default on-disk cache directory.        * Default Cache directory name */private static final String Default_cache_dir = "Volley";      /** * Creates a default instance of the worker pool and calls {@link Requestqueue#start ()} on it.      * May set a maximum size of the disk cache in bytes. * Create a default working pool, and start the request queue * @param context A {@link context} to using for creating the Cache dir. Used to create a cached directory * @param Stac      K an {@link httpstack} to use for the network, or null for default. * @param maxdiskcachebytes The maximum size of the disk cache, in bytes.      Use-1 for default size.      * Hard disk cache maximum, 1 default * @return A started {@link Requestqueue} instance. */public static Requestqueue Newrequestqueue (context context, httpstack stack, int maxdiskcachebytes) {Fil          E Cachedir = new File (Context.getcachedir (), default_cache_dir);//cache queue String useragent = "volley/0"; try {String packagename = conText.getpackagename ();//package name PackageInfo info = Context.getpackagemanager (). Getpackageinfo (PackageName, 0);          useragent = PackageName + "/" + Info.versioncode; } catch (Namenotfoundexception e) {} if (stack = = null) {//If there is no qualified stack if (build.version .              Sdk_int >= 9) {//ADK version at 9 or above stack = new Hurlstack ();                  } else {//Prior to Gingerbread, httpurlconnection is unreliable. see:http://android-developers.blogspot.com/2011/09/androids-http-clients.html stack = new HttpClientS              Tack (Androidhttpclient.newinstance (useragent));                    }} Network Network = new Basicnetwork (stack);          Requestqueue queue;  if (maxdiskcachebytes <=-1)//less than or equal to 1, then the default value {//No maximum size specified queue = new          Requestqueue (New Diskbasedcache (CACHEDIR), network); } else {//Disk cache size Specified queue = new Requestqueue (new Diskbasedcache (Cachedir,          maxdiskcachebytes), network);            } queue.start ();      return queue;   }

  

As you can see, Volley's Newrequestqueue () method creates a stack based on the version (Hurlstack and Httpclientstack, respectively). As for the different ADK versions will create different stacks, is due to the version of Android, the use of hurlstack in more than 9 version is better than Httpclientstack.

Then create the network class Basicnetwork, cache the class Diskbasedcache, and use both to create the Requestqueue object.

Perhaps now we do not understand the role of these two classes, you just need to remember to create requestqueue need these two classes to do.

OK, as the opening article of this column, mainly for everyone to provide reading interest and ideas. In the next article, I will combine the specific source code, to illustrate the specific implementation of volley.

Volle Introduction 02

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.