[Android] Volley source code Analysis (I.) architecture

Source: Internet
Author: User

Volley:google out of a framework for asynchronous processing. Because of its ease of use and good API, it can be widely used. I still as always from the direction of the source to control it. Let's start with a simple code to understand volley

Requestqueue queue = Volley.newrequestqueue (this); Imagerequest imagerequest = new Imagerequest (URL, new Response.listener<bitmap> () {            @Override public            void Onresponse (Bitmap Response) {                //TODO auto-generated method Stub                System.out.println (">>>bitmap =" +response);                }, config.argb_8888,                new Errorlistener () {                    @Override public                    void Onerrorresponse (volleyerror error) {                        TODO auto-generated Method Stub                        System.out.println ("error" +error);                    }                );        Queue.add (imagerequest);

As the saying goes, "For example, beauty", the code framework is the same. Let's think about the tragic experience we used to create Bitmapcache. First we use a single cache function, often just support memory cache, the elimination strategy is generally through the number or capacity limit. Every app you write is a self-made set. In addition, once we are out of the program, we will no longer have access to our bitmap metadata, such as request for network links, resource descriptors, etc., and for the same network request we have to use a separate adorner to intercept.

Of course, I list these out, because in the volley has been a good solution to these problems, when you download the volley source compilation, you will find that volley covers more features than you think. And these things have been well packaged up. And the volley code reads very well, and it's not as smelly and long as some of the native Android code. If volley is a good open source framework, it is better to say that volley is a design pattern that now looks good. And from some of the interfaces provided by volley, volley has already encapsulated a large part of the framework inside, and for API callers it is undoubtedly a boon.

Volley is generally used in the production of consumer models, of course, you say it is the observer is actually understandable. The simple model is used in a variety of frameworks to inform consumers of consumer consumption by producing products. The consumer here is called the request class. This class will be distributed to cachedispatcher and networkdispatcher for consumption. From our experience writing the cache, we are generally consistent with the cache's processing pattern, mostly by seeing if the cache exists and, if so, load from disk. Otherwise, request the network. In fact, volley's treatment is similar. For requests that allow the cache. Request will be distributed to cachedispatcher consumption by Requestqueue. If Cachedispatcher cannot consume, then it will be distributed to Networkdispatcher. This pattern is much like a chain of responsibilities. In fact, in this distribution, there is a volley one of the highlights, is the URL interception. The requestqueue itself maintains a staging list, which can intercept duplicate URL requests very well. requests processed by Cachedispatcher, if present in disk cache, will be parsed via the request's Parsenetworkresponse interface, and we'll take a look at the parse process that requests him for a picture:

Private response<bitmap> Doparse (Networkresponse Response) {byte[] data = Response.data;        Bitmapfactory.options decodeoptions = new Bitmapfactory.options ();        Bitmap Bitmap = null;            if (Mmaxwidth = = 0 && Mmaxheight = = 0) {decodeoptions.inpreferredconfig = Mdecodeconfig;        Bitmap = Bitmapfactory.decodebytearray (data, 0, Data.length, decodeoptions);            } else {//If We have an resize this image, first get the natural bounds.            Decodeoptions.injustdecodebounds = true;            Bitmapfactory.decodebytearray (data, 0, Data.length, decodeoptions);            int actualwidth = Decodeoptions.outwidth;            int actualHeight = Decodeoptions.outheight;            Then compute the dimensions we would ideally as to decode.            int desiredwidth = Getresizeddimension (Mmaxwidth, Mmaxheight, ActualWidth, actualHeight); int desiredheight = Getresizeddimension (mmaxheighT, Mmaxwidth, ActualHeight, actualwidth);            Decode to the nearest power of both scaling factor.            Decodeoptions.injustdecodebounds = false;            TODO (Ficus): Do we need this or are it okay since API 8 doesn ' t support it?            Decodeoptions.inpreferqualityoverspeed = Prefer_quality_over_speed;            Decodeoptions.insamplesize = Findbestsamplesize (ActualWidth, ActualHeight, Desiredwidth, desiredheight);            Bitmap Tempbitmap = bitmapfactory.decodebytearray (data, 0, Data.length, decodeoptions);            If necessary, scale down to the maximal acceptable size.                    if (Tempbitmap! = null && (Tempbitmap.getwidth () > Desiredwidth | |                        Tempbitmap.getheight () > Desiredheight)) {bitmap = Bitmap.createscaledbitmap (Tempbitmap,                Desiredwidth, Desiredheight, true);            Tempbitmap.recycle ();   } else {             bitmap = Tempbitmap;        }} if (bitmap = = null) {return response.error (new ParseError (Response));        } else {return response.success (bitmap, Httpheaderparser.parsecacheheaders (Response)); }    }
We see that it produces a response object that is returned to the upper layer, and finally delivery to distribute the reponse. In fact, we can see that the entire volley cache design is relatively simple, and there is a lot of room for transformation. For example, forthe distribution mechanism of the delivery can be done entirely with event-driven frameworks such as Eventbus. There is also the bitmap generation that can use memory-mapped files to reduce memory overhead. Of course, these little desserts do not affect the existence of volley as a very good code. Inside the volley , the essence of delivery is a thread pool, which uses thread pool post to effectively avoid volley cachedispatcher and networkdispatcher thread blocking due to processing reponse.

We'll look back if we don't exist in the cache and we ask for the network. Volley encapsulates the request interface of the platform, you may be using httpclient, and of course it is possible to use httpurlconnection directly. For the upper level, in order to block out the difference of this platform, abstract a network interface called networks, which is a bridge mode. And when you use some sort of network to get the data, Networkdispatcher put the data into the cache. after distributing the request callback through delivery, Call request's Finish method to remove itself from the Requestqueue staging table.

OK, do not think volley code design is so clear-minded, this chapter we first introduce the main structure of volley, the following will be two chapters to describe the two modules of volley: the cache and network design.


Thx

Non-sub-ink

qq:1025250620





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.