[Android] Volley source code analysis (I) architecture, androidvolley source code

Source: Internet
Author: User
Tags using git

[Android] Volley source code analysis (I) architecture, androidvolley source code

Volley: a google framework for asynchronous processing. Because of its ease of use and good api, it can be widely used. As always, I control the source code. Let's first use a simple piece of 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);            }}, 300,                200,                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, the code framework is also like "The contrast is beautiful. Let's take a look at our past painful experience in creating bitmapcache. First, we use a single cache function, which usually only supports memory cache. The elimination policy is generally limited by quantity or capacity. Each write app has its own set. In addition, once we leave the program, we will no longer obtain the metadata of our Bitmap, such as request network links, resource descriptors, etc, in addition, we must use a separate decorator to intercept requests from the same network.

Of course, the reason why I listed these problems is that Volley has solved these problems well. After you download the Volley source code compilation, you will find that, volley covers far more features than you would consider. And these things have been well encapsulated. Volley's code is also very easy to read, not as smelly and long as some Android native code. If Volley is a good open-source framework, it is better to say that Volley is a set of design patterns that seem good now. In addition, from some interfaces provided by Volley, Volley has encapsulated a large part of it in the Framework, which is undoubtedly a good news for api callers.

Volley generally uses the production consumer model. Of course, you can say that it is an observer. Producers notify consumers of consumption by producing products. This simple model is used in multiple frameworks. The consumer here is the Request class. This class will be distributed to CacheDispatcher and NetworkDispatcher for consumption. From our experience in writing Cache, the processing modes of Cache are generally the same, most of which are based on whether the Cache exists. If so, load from disk. Otherwise, the request network is used. In fact, Volley's processing is similar. For requests that allow Cache. Request will be distributed to CacheDispatcher by RequestQueue for consumption. If CacheDispatcher cannot be consumed, it will be distributed to NetworkDispatcher. This mode is very similar to the responsibility chain. In fact, in this distribution, one of the highlights of Volley is url interception. RequestQueue maintains a temporary list, which can block repeated URL requests. If a Request processed by CacheDispatcher exists in disk cache, it will be parsed through the parseNetworkResponse interface of the Request. Let's take a look at the parse process for requesting an image:

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 to 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 like to decode to.            int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight,                    actualWidth, actualHeight);            int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth,                    actualHeight, actualWidth);            // Decode to the nearest power of two scaling factor.            decodeOptions.inJustDecodeBounds = false;            // TODO(ficus): Do we need this or is 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 can see that it generates a response object and returns it to the upper layer. Finally, Delivery will 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, for the Delivery mechanism of Delivery, event-driven frameworks such as EventBus can be used. In addition, Bitmap can be generated by using memory ing files to reduce memory overhead. Of course, these little desserts do not affect Volley's existence as a very good code. In Volley, Delivery is essentially a thread pool. Using the thread pool post method can effectively avoid thread blocking caused by Volley's CacheDispatcher and NetWorkDispatcher's reponse processing.

Let's look back at the network request if the Cache does not exist. Volley encapsulates the platform's request interfaces. You may use HttpClient, or directly use HttpUrlConnection. For the upper layer, in order to eliminate the differences between such platforms, a Network interface called Network is abstracted, which is a bridge mode. When you obtain data through a network in a certain way, NetworkDispatcher puts the data to the Cache. After the Request callback is distributed through Delivery, call the Request finish method to delete yourself from the temporary table of RequestQueue.

Okay. Do you think Volley's code design is so clear? In this chapter, we first introduce Volley's main structure. The following two chapters describe Volley's two major modules: cache and Network design.







Android source code analysis, how to track the android source code, please take settings as an example, not too good for beginners, please instruct the settings code to load the eclipse project to add the relevant jar package slowly from the entrance to study Bai
For details about how to conduct android source code analysis, you need to refer to the architecture diagram provided by google. For details about the structure, please refer to the following link: the source code project is used separately for Android projects. Import all Android source codes to Eclipse before using git. download the source code. Search a lot on the Internet and try it by yourself.

Related Article

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.