Android Image level Three caching strategy and implementation

Source: Internet
Author: User
Tags md5 object object
Preface:

The level three cache here refers to the three levels of memory caching, file caching, and networking.

In general, we load pictures for the first time, memory and files are not cached, so we need to load from the network, after loading, we will save to memory and file; When the picture is loaded again, we will first look for the memory there is no, if there is a direct display of memory pictures, if not, We will then find out if there are any in the file, and if so, we will display the picture in the file and save it in memory so that we can find it in memory next time.

The reason we want to do caching is mainly to improve efficiency and save traffic. But why do you have to do level three? Why not just exist in memory or just exist in a file. This is because the memory of fast reading, but easy to be recycled, small capacity, file reading speed, but the capacity of large, not to be recycled.

With the above introduction, we already know the need for level three caching and implementation steps, next, we will choose the cache policy at each level.

Memory cache, at the beginning, it is recommended to use Softrefrence (soft reference), it only in the case of insufficient memory will be GC recovery. But newer Android systems tend to recycle softrefrence, which makes softrefrence less useful. However, Android provided LRUCache after 3.0, using the least recent phase-out strategy. In this article, our memory cache uses LRUCache.

File caching, we are using the Disklrucache click here to download

Network request, here we use Volley Network request frame Click here to download . I don't know, I can see here. Android volley Getting Started to Excel: Customizing your own request

Click here to download the source code memory Cache LRUCache We define the Imagecacheutil class for the image cache, it implements the volley Imageloader.imagecache interface, the interface needs to implement two methods: 1.getbitmap:volley request will be the first callback Getbitmap see if the cache has a picture, no words will go to the network request 2.putbitmap:volley Download the picture callback, implementation of the method can be a picture cache
The following steps are required to use LRUCache 1. An instance of LRUCache obtained by new LRUCache

        Gets 1/8 of the memory that can be used as cache
        int maxSize = (int) (Runtime.getruntime (). MaxMemory ()/8);
        Instantiating the Lrucaceh object
        mlrucache = new lrucache<string, bitmap> (maxSize) {
                @Override
                protected int sizeOf ( String key, Bitmap Bitmap) {return
                bitmap.getrowbytes () * Bitmap.getheight ();
            }
        };
2. In the Getbitmap function through the Mlrucache.get (URL) to get the memory of the picture, no time returned empty. 3. In the Putbitmap function, the picture is stored in memory through Mlrucache.put (URL,BITMAP). The specific usage can look at the code I posted below. File Cache DisklrucacheUsing Disklrucache requires the following steps: 1. Through Disklrucache.open (...) Get an example of Disklrucache
        Disklrucache instance, its construction method is private, so we need to generate it through the open method provided by it.

        try {
            Mdisklrucache = Disklrucache.open (Getdiskcachedir (Myapplication.getcontext (), Cache_folder_name),
                    getappversion (Myapplication.getcontext ()), 1, diskmaxsize);
        catch (IOException e) {
            e.printstacktrace ();
        }
2. In the Getbitmap function, if the Mlrucache.get (URL) returns empty, the Disklrucache.snapshot is obtained through Mdisklrucache.get (key) through Bitmapfratory ( Snapshot.getinputstream (0)) get picture, no time return empty
            String Diskkey = MD5UTILS.MD5 (s);
            try {
                if (Mdisklrucache.get (diskkey)!= null) {//file with//
                    from File
                    log.d (TAG, "take from File");
                    Disklrucache.snapshot Snapshot = Mdisklrucache.get (Diskkey);
                    Bitmap Bitmap = null;
                    if (snapshot!= null) {
                        bitmap = Bitmapfactory.decodestream (snapshot.getinputstream (0));
                        Deposit Memory
                        Mlrucache.put (S,BITMAP);
                    }
                    return bitmap
                }
            } catch (IOException e) {
                e.printstacktrace ();
            }
3. In the Putbitmap function, if Mdisklrucache.get (key) ==null, the picture is saved to the file.
        Deposit file
        String Diskkey = MD5UTILS.MD5 (s);
        try {
            if (mdisklrucache.get (diskkey) = null) {
                LOG.D (TAG, "Deposit file");
                Disklrucache.editor Editor = Mdisklrucache.edit (Diskkey);
                if (editor!= null) {
                    OutputStream outputstream = editor.newoutputstream (0);
                    if (bitmap.compress (Bitmap.compressformat.jpeg,100,outputstream)) {
                        editor.commit ();
                    } else{
                        Editor.abort ();
                    }
                Mdisklrucache.flush ();
            }
        catch (IOException e) {
            e.printstacktrace ();
        }

Here's what this imagecacheutil class is all about.

public class Imagecacheutil implements Imageloader.imagecache {//cache class private static lrucache<string, Bitmap&gt ;
    Mlrucache;

    private static Disklrucache Mdisklrucache;

    Disk Cache size private static final int diskmaxsize = 10 * 1024 * 1024;

    Path private static String Cache_folder_name = "Yr_imagecache";

    Private String TAG = ImageCacheUtil.class.getSimpleName ();
        Public Imagecacheutil () {//Get 1/8 of the memory to be applied as cache int maxSize = (int) (Runtime.getruntime (). MaxMemory ()/8);
                Instantiate Lrucaceh Object mlrucache = new lrucache<string, bitmap> (maxSize) {@Override protected int sizeOf (String key, Bitmap Bitmap) {return bitmap.getrowbytes () * Bitmap.getheigh
            T ();

        }
        };

        Disklrucache instance, its construction method is private, so we need to generate it through the open method provided by it.
                    try {Mdisklrucache = Disklrucache.open (Getdiskcachedir (Myapplication.getcontext (), Cache_folder_name), GEtappversion (Myapplication.getcontext ()), 1, diskmaxsize);
        catch (IOException e) {e.printstacktrace ();
    }/** * Volley request will be the first callback getbitmap see if there is a picture in the cache, no more requests * @param s * @return * * * @Override Public Bitmap Getbitmap (String s) {if (Mlrucache.get (s)!= null) {//memory has//gets LOG.D from memory (TA
            G, "Get from Memory");
        return Mlrucache.get (s);
            }else {String Diskkey = MD5UTILS.MD5 (s); try {if (Mdisklrucache.get (diskkey)!= null) {//file has///is taken from the file log.d
                    (TAG, "take from File");
                    Disklrucache.snapshot Snapshot = Mdisklrucache.get (Diskkey);
                    Bitmap Bitmap = null;
                        if (snapshot!= null) {bitmap = Bitmapfactory.decodestream (snapshot.getinputstream (0));
                    Depositing memory mlrucache.put (S,BITMAP);
     }               return bitmap;
            } catch (IOException e) {e.printstacktrace ();
        } log.d (TAG, "take from Network");
    return null; /** * When volley download the picture, the Putbitmap method will be adjusted back and forth to cache the picture * @param s * @param bitmap/@Override Publ
        IC void Putbitmap (String s, Bitmap Bitmap) {//Memory log.d (TAG, "Deposit memory");
        Mlrucache.put (S,BITMAP);
        Deposit file String Diskkey = MD5UTILS.MD5 (s);
                try {if (mdisklrucache.get (diskkey) = null) {LOG.D (TAG, "Deposit file");
                Disklrucache.editor Editor = Mdisklrucache.edit (Diskkey);
                    if (editor!= null) {OutputStream outputstream = editor.newoutputstream (0);
                    if (bitmap.compress (Bitmap.compressformat.jpeg,100,outputstream)) {editor.commit ();
                    }else{Editor.abort (); }
                } mdisklrucache.flush ();
        } catch (IOException e) {e.printstacktrace (); }//This method will determine whether the current SD card exists, and then select the cached address public File Getdiskcachedir (context context, String UniqueName) {Stri
        Ng CachePath; if (Environment.MEDIA_MOUNTED.equals (Environment.getexternalstoragestate ()) | |!
        Environment.isexternalstorageremovable ()) {CachePath = Context.getexternalcachedir (). GetPath ();
        else {CachePath = Context.getcachedir (). GetPath ();
        } log.d (Tag,cachepath + file.separator + uniquename);
    return new File (CachePath + file.separator + uniquename); //Get Application version number public int Getappversion (context context) {try {packageinfo info = Contex
            T.getpackagemanager (). Getpackageinfo (Context.getpackagename (), 0);
        return info.versioncode;
     catch (Packagemanager.namenotfoundexception e) {       E.printstacktrace ();
    return 1; }
}
Volley Download PicturesI do not know volley can read this blog: Android Volley primer to proficient: Customize their request for the volley to download the specific photos can read this blog: Android Volley entry to Mastery: Load network pictures with volley Volley requires us to declare a requestqueue to maintain the request queue, and we define requestqueuemanager for management.
public class Requestqueuemanager {public
    static requestqueue Mrequestqueue = Volley.newrequestqueue ( Myapplication.getcontext ());
    public static void Addrequest (Request<?> Request, Object object) {
        if (object!= null) {
            Request.settag ( object);
        }
        Mrequestqueue.add (request);
    }
    public static void Cancelall (Object tag) {
        mrequestqueue.cancelall (tag);
    }
Volley gives us Imageloader classes and Imagecache classes for picture downloads. We can use the Imageloader get (url,imageloader.imagelisteer,width,height) method to download the picture Imageloader using the following steps: 1. With new An example of Imageloader is obtained by Imageloader method. Where the construction method needs to be passed in Requestqueue and Imagecache (the Imagecaheutil class that we introduced the memory implemented Imagecache)
  private static Imagecacheutil Mimagetcache = new Imagecacheutil ();

  public static Imageloader Mimageloader = new Imageloader (Requestqueuemanager.mrequestqueue,mimagetcache);
2. Use get method to download picture
    public static void LoadImage (String url,imageloader.imagelistener imagelistener) {
        mimageloader.get (URL, imagelistener,0,0);
    }

    public static void LoadImage (String url,imageloader.imagelistener imagelistener,int maxwidth,int maxheight) {
        Mimageloader.get (url,imagelistener,maxwidth,maxheight);
    }
3. Invoking in the activity
        Imagecachemanager.loadimage ("Http://img0.bdstatic.com/img/image/shouye/xiaoxiao/%E5%AE%A0%E7%89%A983.jpg",
                New Imageloader.imagelistener () {
                    @Override public
                    void Onresponse (Imageloader.imagecontainer Imagecontainer, Boolean b) {
                        progressly.setvisibility (view.gone);
                        if (Imagecontainer.getbitmap ()!= null) {
                            imageview.setimagebitmap (Imagecontainer.getbitmap ());
                        }
                    }

                    @Override public
                    void Onerrorresponse (Volleyerror volleyerror) {
                        progressly.setvisibility (view.gone);
                    }
                });
OK, that's the implementation of the Android three cache. Download Source Click here




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.