Volley Framework Anatomy (ii) from start to finish

Source: Internet
Author: User

In the previous article, we analyzed a general composition of volley. Today we continue to analyze a flow of volley, from initialization to initiating a request, to the end of a request.

First look at initialization.
The initialization of volley, in effect, is to return a requestqueue queue. Called in the volley. One of the simplest ways to create one is to have a context.

/**     * Creates a default instance of the worker pool and calls {@link RequestQueue#start()} on it.     *     * @param context A {@link Context} to use for creating the cache dir.     * @return A started {@link RequestQueue} instance.     */    publicstaticnewRequestQueue(Context context) {        returnnull);    }

Our analysis is certainly not point-to-stop, so we focus on the most parametric constructors.

/** * Creates adefaultInstance ofThe worker Pool andCalls {@link Requestqueue#start ()} on it. * May set a maximum size ofThe disk cacheinchbytes. * * @param context A {@link context} to  Use  forCreating the Cache dir. * @param stack an {@link httpstack} to  Use  forThe network,or NULL  for default. * @param maxdiskcachebytes the maximum size ofThe disk cache,inchbytes. Use-1  for defaultSize. * @returnA started {@link Requestqueue} instance. */ Public StaticRequestqueue Newrequestqueue (context context, httpstack stack, int maxdiskcachebytes) {File Cachedir =NewFile (Context.getcachedir (), default_cache_dir); String useragent ="volley/0";Try{String PackageName = Context.getpackagename (); PackageInfo info = Context.getpackagemanager (). Getpackageinfo (PackageName,0); useragent = PackageName +"/"+ Info.versioncode; } catch (Namenotfoundexception e) {}if(Stack = =NULL) {if(Build.VERSION.SDK_INT >=9) {stack =NewHurlstack (); }Else{//Prior to Gingerbread, HttpURLConnection was unreliable.                //See:http://android-developers.blogspot.com/2011/09/androids-http-clients.htmlstack =NewHttpclientstack (Androidhttpclient.newinstance (useragent)); }} Network Network =NewBasicnetwork (stack); Requestqueue queue;if(Maxdiskcachebytes <=-1)        {//No maximum size specifiedQueue =NewRequestqueue (NewDiskbasedcache (Cachedir), network); }Else{//Disk cache size specifiedQueue =NewRequestqueue (NewDiskbasedcache (Cachedir, maxdiskcachebytes), network); } queue.start ();returnQueue }

This method has three parameters Context,httpstack and maxdiskcachebytes.
That's what I said. Httpstack is an interface for specific implementations of HTTP requests, and maxdiskcachebytes is used to create disk caches to set the maximum cache capacity.

The interesting thing about initialization is that it customizes a useragent, which is used in the HTTP header to indicate that the current request is being initiated by the current software, which makes it easier to find problems and statistics later. It is also recommended that you use your own UA instead when creating network requests. By experience, UA is usually composed of software (framework) name + version + additional information.

Creating an HTTP request here also distinguishes the SDK VERSION below 9 and 9.
For more than 9 of the version, directly used HttpURLConnection , for the version below 9 used AndroidHttpClient , for what reason, can refer to: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
As this article needs to be turned over the wall, here are the main points I have listed below:

1. HttpURLConnection is a lightweight HTTP connection scheme, suitable for most applications, it supports stream compression with network cache, can reduce network traffic and save Battery,
So it is recommended to use this API for gingerbread and above.
2. Below gingerbread, HttpURLConnection when the Close method is called on a stream that has not yet been read, the portion of the stream that is not read is cached and then added to the next requested data area, resulting in a data error for the next request.
3. AndroidHttpClient complex scalability is good and stable, but androidteam is difficult to improve some features while ensuring compatibility, so it is not generally recommended.

Of course, if you are expanding after yourself, the one that implements the Httpstack object will not go into the logic above.

After the Httpstack object is obtained from the version, it is passed as a parameter to the default implementation Basicnetwork object for network. That is, the basicnetwork is actually a wrapper over the Httpstack (of course, if you implement the other network, you do not necessarily need this httpstack).

After that, a disk cache was created based on Maxdiskcachebytes.

Finally, start the requestqueue.
Two things were done at startup, creating Cachedispatcher and Networkdispatcher. Both of these are subclasses of the thread class, and the Cachedispatcher threads are primarily in the role of local IO operations, which are loaded with caching. Networkdispatcher threads perform network operations primarily, creating 1 cache threads and 4 network threads by default.

After initialization is complete, you can use Requestqueue to initiate a network request.

The initiating request starts with the Add method of the Requestqueue.


http://img.blog.csdn.net/20150425163836789

Process, for example, is simple. Here are some interesting details.
In the first line of the add code, we see that the request has passed the Requestqueue to the object and is saved as a member variable. Then why? Because the life cycle of the request is maintained by some method of the request, it has nothing to do with this queue, but at the end of a request it needs to be removed from the queue and it needs this reference to do the removal. You can see the code for Request.finish.

ifnull) {            mRequestQueue.finish(this); }

Each request has a unique serial number, which is implemented using Atomicinteger.

privatenew AtomicInteger();  /**     * Gets a sequence number.     */publicintgetSequenceNumber() {        return mSequenceGenerator.incrementAndGet(); }

In cases where there is no proactive prioritization, this is handled as the priority of the request. That is, the smaller the number, the higher the priority.

Another interesting point is that the request log system, all state changes, will have event records in order to track the problem.

As can be seen, such as cache hit situation, network requests, retry situations, etc., are recorded.

Volley the logic of avoiding repeated requests to conserve network resources is very tricky to write. There is a clever use of an empty value to handle, you can produce a list object less.

  //Insert request to stage if there ' s already a request with the same cache key in flight.Synchronized (mwaitingrequests) {String CacheKey = Request.getcachekey ();if(Mwaitingrequests.containskey (CacheKey)) {//There is already a request in flight. Queue up.Queue<request<?>> stagedrequests = Mwaitingrequests.get (CacheKey);if(Stagedrequests = =NULL) {stagedrequests =NewLinkedlist<request<?>> ();                } stagedrequests.add (Request); Mwaitingrequests.put (CacheKey, stagedrequests);if(volleylog.debug) {VOLLEYLOG.V ("Request for cachekey=%s are in flight, putting on hold.", CacheKey); }            }Else{//Insert ' null ' queue for this cacheKey, indicating there are now a request in                //flight.Mwaitingrequests.put (CacheKey,NULL);            Mcachequeue.add (Request); }

If it is the first request, put a null value directly, the second time if it is the same request, it will add a linked list to cache the same requests. When the first request network is completed, it will add all the requests in the list to the cache queue. In this way, the same request can be guaranteed in a short time, and only one of the actual network resources will be used, and the same request will not be discarded.

Many of volley's details are worth learning. Next time we analyze some of the important classes.

Volley Framework Anatomy (ii) from start to finish

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.