Volley Full Parse

Source: Internet
Author: User

What is volley? 1. Introduction

?? Volley is Goole launched a new network communication framework at the 2013 Google I/O Conference, which is open source. From the name of the origin and map of countless rapid rockets can be seen volley characteristics: especially suitable for small data volume, communication frequent network operation. (individuals think that the vast majority of network operations in Android apps belong to this type).

?? The volley load image implements a level two cache (network cache, file cache), and no memory cache is implemented. Volley has encapsulated various asynchronous tasks and picture samples. The memory cache uses the LRUCache class implementation, which we need to add manually. The soft reference cache is not used. Because the Android system after 4.0 has not recommended the use of soft reference cache.

2, the overall design of volley

3. What volley can do

Asynchronous download of JSON, image, etc.;
Handle network requests such as GET, post, etc.;
Ordering of network requests (scheduling);
Priority processing of network requests;
Cache
Multi-level cancellation requests;
Interaction with activity and life cycle (simultaneous cancellation of all network requests at the end of activity);
Wait a minute.

Second, the image of the three-level cache in the implementation of volley

?? In fact, volley can completely replace our handwritten level three cache, because Google has a very good package of volley, as described below:

1. Recommended usage of volley-singleton mode

?? When using volley, we recommend encapsulating the use of volley into a single case. Initialize it in the application. The specific code is as follows:

Single Example:

 PackageCom.ht.xiangqu.util;ImportAndroid.content.Context;ImportAndroid.graphics.Bitmap;ImportAndroid.support.v4.util.LruCache;ImportCom.android.volley.RequestQueue;ImportCom.android.volley.toolbox.ImageLoader;ImportCom.android.volley.toolbox.Volley;/** * Created by Annuo on 2015/6/16. * * Public  class requestmanager {    Private StaticRequestmanager ourinstance;PrivateRequestqueue Requestqueue;PrivateImageloader Imageloader; Public StaticRequestmanagerCreateInstance(Context context) {if(Context! =NULL) {if(Ourinstance = =NULL) {ourinstance =NewRequestmanager (context); }Else{Throw NewIllegalArgumentException ("Context must be set"); }        }returnOurinstance; } Public StaticRequestmanagergetinstance() {returnOurinstance; }Private Requestmanager(Context context)        {Requestqueue = Volley.newrequestqueue (context); Imageloader =NewImageloader (Requestqueue,NewImageloader.imagecache () {Privatelrucache<string, bitmap> cache =NewLrucache<> ( -);@Override                     PublicBitmapGetbitmap(String URL) {returnCache.get (URL); }@Override                     Public void Putbitmap(String URL, Bitmap Bitmap)                    {cache.put (URL, bitmap);    }                }        ); } PublicRequestqueueGetrequestqueue() {returnRequestqueue; } PublicImageloaderGetimageloader() {returnImageloader; }}

Application:

package com.ht.xiangqu.util;import android.app.Application;import android.util.Log;/** * Created by annuo on 2015/6/16. */publicclass MainApplation extends Application {    @Override    publicvoidonCreate() {        super.onCreate();        RequestManager.createInstance(getApplicationContext());        Log.d("nihao""nihao");    }}
2. Memory Cache

?? The memory cache is only available when the image is loaded, and the string is usually followed by the file cache.

?? Google does not automatically help us to implement the memory cache, we need to manually join in. The memory cache is already represented in the Singleton class (i.e., LRUCache), and we do not have to add the memory cache each time we use it. LRUCache This class is available in the Android3.1 version, if you are developing in an earlier version of Android, you will need to import the ANDROID-SUPPORT-V4 jar package.

3. File cache

?? Volley has already implemented the cache for our files by default. Let's look through the source code:

    /**     * Constructs a new ImageLoader.     * @param queue The RequestQueue to use for making image requests.     * @param imageCache The cache to use as an L1 cache.     */    publicImageLoader(RequestQueue queue, ImageCache imageCache) {        mRequestQueue = queue;        mCache = imageCache;    }

?? The above code is a piece of code in Imageloader, from which we can see that when constructing imageloader, we have established a L1 level cache (file cache) by default.

So where exactly is the volley cache file? See:

?? The exact location is in the location. That is, the package name of the data/data/application/volley, if the volley cache location is not modified, the default name is volley.

4, the picture of the two sampling problem

?? In fact, volley default has helped us to do a picture of the two samples, just need us to make the request, add more than two parameters. We generally ignore this problem, and finally lead to the constant oom.

    /**     * 这是访问网络图片的核心方法     * @param requestUrl     * @param imageListener     * @param maxWidth     * @param maxHeight     * @return     */    publicget(String requestUrl, ImageListener imageListener,            intint maxHeight) {
Request<?> newrequest =NewImagerequest (Requesturl,NewListener<bitmap> () {@Override                 Public void Onresponse(Bitmap response)                {ongetimagesuccess (CacheKey, response); }}, MaxWidth, MaxHeight, config.rgb_565,NewErrorlistener () {@Override                 Public void Onerrorresponse(Volleyerror error)                {Ongetimageerror (CacheKey, error);        }            });        Mrequestqueue.add (newrequest); Minflightrequests.put (CacheKey,NewBatchedimagerequest (Newrequest, Imagecontainer));returnImagecontainer; }

?? The above code is the core method of Imageloader, where two parameters are maxwidth,maxheight, and we generally ignore these two parameters. The default value is 0 and 0, so that the two sampling algorithm will not work, we get the picture is from the server 1:1 where. But in general, we set these two parameters, we can get the picture that we want to reduce the proportion. This will completely avoid the oom.

Iii. other problems of volley 1, fillet picture problem
     Public StaticImagelistenerGetimagelistener(FinalImageView View,Final intDefaultimageresid,Final intERRORIMAGERESID) {return NewImagelistener () {@Override             Public void Onerrorresponse(Volleyerror error) {if(Errorimageresid! =0) {View.setimageresource (ERRORIMAGERESID); }            }@Override             Public void Onresponse(Imagecontainer response,BooleanIsimmediate) {if(Response.getbitmap ()! =NULL) {//Can be set here, if you want to get a picture of the fillet, you can process the bitmap, you can give ImageView plus a                    //Additional parametersView.setimagebitmap (Response.getbitmap ()); }Else if(Defaultimageresid! =0) {View.setimageresource (DEFAULTIMAGERESID);    }            }        }; }
2. When the ListView is reused, it solves the problem of picture dislocation.
    /** * Use this method to solve the problem of picture confusion * @param View * @param defaultimageresid * @param Err Orimageresid * @param URL * @return  * *     Public StaticImagelistenerGetimagelistener(FinalImageView View,Final intDefaultimageresid,Final intErrorimageresid,FinalString URL) {return NewImagelistener () {@Override             Public void Onerrorresponse(Volleyerror error) {if(Errorimageresid! =0) {View.setimageresource (ERRORIMAGERESID); }            }@Override             Public void Onresponse(Imagecontainer response,BooleanIsimmediate) {if(Response.getbitmap ()! =NULL) {//Can be set here, if you want to get a picture of the fillet, you can process the bitmap, you can give ImageView plus a                    //Additional parametersString Urltag = (string) view.gettag ();if(urltag!=NULL&& Urltag.trim (). Equals (URL)) {View.setimagebitmap (Response.getbitmap ()); }                }Else if(Defaultimageresid! =0) {View.setimageresource (DEFAULTIMAGERESID);    }            }        }; }
Iv. specific usage of volley

?? On this piece of content, the network has a lot of information, in short volley use very simple, interested can go to the network to find relevant information to learn. The loading speed of the volley is absolutely unexpected.

--Know who you are, what you want, how high you can jump, and dare to jump and bear all the results of a possible failure.

Volley Full Parse

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.