Android Volley analysis (i)

Source: Internet
Author: User

Volley is a network communication library under the Android system, providing Android with simple and fast network operation (Volley:esay, Fast Networking for Android), the following is its structure:


Since it is a network communication library, it will naturally involve the basic operation of the network: request and response, but also the most basic concept. The client makes the request, the server returns the byte data of the response, and the client resolves the desired result. Volley How to design these basic concepts?

One, the component

1. Network

Definition of network operation, incoming request requests, get response networkresponse

Public interface Network {    /**     * performs the specified request.     * @param request Request to process     * @return A {@link networkresponse} with data and caching metadata; 'll never be Null     * @throws volleyerror on Errors     *    /Public networkresponse performrequest (request<?> Request) Throws Volleyerror;}

2. Request

Request definition, parameters of network request, address, and other information

Public Request (int method, String URL, Response.errorlistener listener) {        Mmethod = method;        Murl = URL;        Merrorlistener = listener;        Setretrypolicy (New Defaultretrypolicy ());        Mdefaulttrafficstatstag = Finddefaulttrafficstatstag (URL);    }

There are two abstract methods in request that require subclasses to implement,

One is parsenetworkresponse, that is, for the returned data, how to parse and parse into what type of data. A specific request, you should know what you want results, such as Stringrequest is to parse the results into a string, and Imagerequest is to parse the results into bitmap;

The other is Deliverresponse, which is used to pass the results when parsing is complete. Here is the parsed result, the subclass is responsible for processing the returned parse results, usually in the inside through the listener return to the application scenario.

/**     * Subclasses must implement this to parse the RAW network response     * and return an appropriate response type. This method would be is     * called from a worker thread.  The response is not being delivered     * if you return null.     * @param response response from the network     * @return The parsed response, or null in the case of an error    */ Abstract protected response<t> parsenetworkresponse (Networkresponse Response);        /**     * Subclasses must implement this to perform delivery for the parsed     * response to their listeners.  The given response is guaranteed to     * was non-null; responses that fail to parse was not delivered.     * @param response The parsed response returned by     * {@link #parseNetworkResponse (networkresponse)}    */ Abstract protected void Deliverresponse (T response);

3, Networkresponse

Network request generic return result, stored in data

    Public networkresponse (int statusCode, byte[] data, map<string, string> headers,            boolean notmodified) {        This.statuscode = StatusCode;        This.data = data;        This.headers = headers;        this.notmodified = notmodified;    }


4, Response<t>

Package of response results, end result, cache structure cacheentry, error message Error

Private Response (T result, Cache.entry cacheentry) {        This.result = result;        This.cacheentry = CacheEntry;        This.error = null;    }

II. process of implementation

With the basic data structure above, it is then considered how to manipulate these structures to complete the process from request to response. This is the core of the whole volley, but also embodies the author's design ideas of the part, involving task scheduling, asynchronous processing and so on.

1, Requestqueue

Request queue, all requests are added to the internal queue by Requestqueue's Add method, and the finish method is called to move the request out of the request queue when the request ends up with the response result.

The following members are included in the Requestqueue:

    • Cache caching structure for caching response results;
    • Implementation of network operation
    • Networkdispatcher Network Task Scheduler
    • Cachedispatcher Cache Task Scheduler
    • Responsedelivery response post for transferring results from worker threads to the UI thread
    • Cachequeue Cache Task Queue
    • Networkqueue Network Task Queue

Requestqueue completes two tasks:

To start and stop the scheduler:

/** * Starts the dispatchers in this queue.  */public void Start () {Stop ();        Make sure any currently running dispatchers is stopped.        Create the cache dispatcher and start it.        Mcachedispatcher = new Cachedispatcher (Mcachequeue, Mnetworkqueue, Mcache, mdelivery);        Mcachedispatcher.start ();        Create network dispatchers (and corresponding threads) up to the pool size. for (int i = 0; i < mdispatchers.length; i++) {Networkdispatcher networkdispatcher = new Networkdispatcher (            Mnetworkqueue, Mnetwork, Mcache, mdelivery);            Mdispatchers[i] = Networkdispatcher;        Networkdispatcher.start ();     }}/** * Stops the cache and network dispatchers.        */public void Stop () {if (mcachedispatcher! = null) {mcachedispatcher.quit (); } for (int i = 0; i < mdispatchers.length; i++) {if (mdispatchers[i]! = null) {MDIspatchers[i].quit (); }        }    }

The request is added to the appropriate queue, and the individual schedulers are then taken out of their own processing

    Public <T> request<t> Add (request<t> request) {//Tag the Request as belonging-to-this queue        and add it to the set of current requests.        Request.setrequestqueue (this);        Synchronized (mcurrentrequests) {mcurrentrequests.add (request);        }//Process requests in the order they is added.        Request.setsequence (Getsequencenumber ());        Request.addmarker ("Add-to-queue");        If the request is uncacheable, skip the cache queue and go straight to the network.            if (!request.shouldcache ()) {mnetworkqueue.add (request);        return request;        }//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 = new linkedlist<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 R                Equest in//flight.                Mwaitingrequests.put (CacheKey, NULL);            Mcachequeue.add (Request);        } return request; }    }

As can be seen above, a request does not require caching will be directly added to the networkqueue, otherwise it will be added to the cachequeue. How is the dispatcher going to take it out and handle it on its own?

2, Cachedispatcher,networkdispatcher

The scheduler is a thread, the queue is blocked, there is a request to execute, no wait. For the cache scheduler Cachedispatcher, if no response results are found in the cache, the request is added to the network scheduler Networkdispatcher

while (true) {try {//Get a request from the cache triage queue, blocking until                At least one is available.                Final request<?> Request = Mcachequeue.take ();                Request.addmarker ("Cache-queue-take");                If the request has been canceled, don ' t bother dispatching it.                    if (request.iscanceled ()) {request.finish ("cache-discard-canceled");                Continue                }//Attempt to retrieve the item from cache.                Cache.entry Entry = Mcache.get (Request.getcachekey ());                    if (entry = = null) {Request.addmarker ("Cache-miss"); Cache Miss;                    Send off to the network dispatcher.                    Mnetworkqueue.put (Request);                Continue                }//If It is completely expired, just send it to the network. if (entry.isexpired ()) {Request.addmarker ("cache-hit-expired");                    Request.setcacheentry (entry);                    Mnetworkqueue.put (Request);                Continue }//We have a cache hit;                The parse its data for delivery the request.                Request.addmarker ("Cache-hit"); response<?> Response = request.parsenetworkresponse (New Networkresponse (Entry.data, Entry.re                Sponseheaders));                Request.addmarker ("cache-hit-parsed"); if (!entry.refreshneeded ()) {//Completely unexpired cache hit.                    Just deliver the response.                Mdelivery.postresponse (request, response); } else {//soft-expired cache hit.                    We can deliver the cached response,//But we need to also send the request to the network for                    refreshing. Request.addmarker ("Cache-hit-refresh-needed ");                    Request.setcacheentry (entry);                    Mark the response as intermediate.                    Response.intermediate = true; Post the intermediate response back to the user and has///the delivery then forward the request AL                    Ong to the network. Mdelivery.postresponse (Request, Response, new Runnable () {@Override public                            void run () {try {mnetworkqueue.put (request);                            } catch (Interruptedexception e) {//Not much we can does about this.                }                        }                    }); }

Networkdispatcher is responsible for performing a network operation to obtain a response, invoking the request resolution response to get the specified return data type, adding the result to the cache, and using delivery to return the result to the UI thread.


Android Volley analysis (i)

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.