About level three cache in Android

Source: Internet
Author: User

The three-level cache is presented to enhance the user experience. When we first open the app to get pictures, first go to the network to download pictures, then into the memory cache, disk cache, when we need to use the image just downloaded, there is no need to repeat to the network to download, directly from the memory cache and the disk cache, due to the memory cache faster, We prefer to look for the image in the memory cache, if it is found, if not found (the memory cache size is limited), then we go to the disk cache to find. As long as we are reasonably able to coordinate this three-tier cache application, you can improve application performance. A level three cache refers to the memory cache, the local cache, and the network cache. Their respective characteristics are the memory cache speed, priority to read, local cache speed second, memory is not, read local, the network cache speed is the slowest, not local, only to access the network. For the network cache, it is easier to get the resources directly from the network, the local cache can exist in the SD card, the memory cache usually exists in the array or the collection. It is important to note that the life cycle of arrays and collections depends on the activity in which it exists, so when the program exits, the resources in the array and the collection are generally freed. Before you know how the level three cache works, there are a few concepts that need to be introduced first.

Instances and objects:
An object is an instance of a class, and the process of creating an object is also called an instantiation of the class. Objects are created with a class as a template. This will use the heap to store an instance of the object at the bottom of the Android stack to store the object of the class. References refer to the instantiation of some objects that require other object instances, such as the ImageView of a context object, which means that ImageView holds a reference to the context (ImageView holds a reference to context )。

Garbage collection Mechanism (GC):
The virtual machine free memory space, that is, the object in the heap space is recognized, if the object is being referenced, it is called a living object, conversely, if the object is no longer referenced, then garbage object, you can reclaim its occupied space for redistribution. More specifically, for GC, when a programmer creates an object, the GC starts to monitor the object's address, size, and usage. Typically, a GC uses a graph to record and manage all objects in the heap in such a way as to determine which objects are "up to" and which are "unreachable". Garbage collection occurs when an object is not reached, that is, when the object is no longer referenced. This mechanism marks the memory in the virtual machine and determines which memory needs to be recycled, automatically reclaims the memory based on a certain recycling strategy, and never Stops (Nerver Stop) to ensure that the memory space in the virtual machine is protected from memory leaks and overflow problems.

Memory leaks:
When an instance is no longer needed, but the object is still referenced, this is called a memory leak (Leak). The Android virtual machine allocates a certain amount of memory space for each application, and when memory leaks reach a certain level, memory overflows.

       references to memory:
          The reference levels for memory include strong references, soft references, weak references, and virtual references. Strong references are the default way of referencing, and are not recycled even if memory overflows. Soft references (softreference), when memory is insufficient, will consider recycling. When weak reference (WeakReference) memory is insufficient, recycling is considered. When the virtual reference (phantomreference) memory is not enough, the first consideration is recycling! In general, the references we commonly use are strong references, such as references to create a member variable. For GC, the strength of softreference is significantly lower than that of srongreference. SoftReference decorated reference, which tells the GC: I am a soft reference, when the memory is low, I point to the memory can be released to you. Generally, it is not necessary to use this memory resource, or some cached variables that consume a lot of memory resources, you need to consider softreference. For GC, the intensity of weakreference is significantly lower than that of SoftReference. WeakReference decorated the reference, which tells the GC: I am a weak reference, for your request I have no words, I point to this memory is can be released to you. The virtual reference is not the same as the various references mentioned above, he is mainly to track when an object is collected by GC. It's also useful in Android: Filecleaner.java. These references to avoiding memory overflows are no longer useful on Android 2.3+ because the garbage collector frequently recycles objects that are not strongly referenced, and Android officially recommends using LRUCache. So when we use soft references for memory caching, we find that in-memory resources are frequently recycled by the system. Finally, the data is read locally.

So that we can understand the level three cache very well. First, read the data in memory. In-memory read data requires the least recent reference algorithm (LRUCache). The LruCache algorithm requires the new lrucache<string, bitmap> () to pass in a maximum memory allocated to the software, while rewriting the sizeof () method to calculate the size of each picture. This allows you to call LRUCache's put () and get () methods directly. When no data is found in memory, locate the storage file in the SD card. Write data to the folder through the bitmap compress () method, read the data through the bitmap factory bitmapfactory Decodestream (), and pass in the options parameter for the Decodestream () method to reduce the picture. Finally, if the data is still not available locally, it is obtained from the network. Network fetch data can be performed with asynchronous tasks (time-consuming operations can no longer be performed in the main thread). Asynchronous tasks require overriding the OnPostExecute () method and the Doinbackground () method. The Doinbackground () method accesses the network, where the httpurlconnection is used to get the input stream through the connection, using the bitmap factory to convert to a bitmap and back. The OnPostExecute () method executes after the Doinbackground () method executes, passing in the return value of the number of arguments Doinbackground () method.

Next comes the code, which is how I invoke the tool class:

Import Android.os.bundle;import Android.support.v7.app.appcompatactivity;import Android.widget.imageview;import Com.example.huang.demo.utils.cacheutils;public class Mainactivity extends appcompatactivity {    private static Final String TAG = "mainactivity";    Private ImageView IV;    @Override    protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);        Getbitmap ();    }    private void Getbitmap () {        IV = (ImageView) Findviewbyid (R.ID.IV);        Cacheutils utils = new Cacheutils ();        Utils.diaplay (iv, "Http://192.168.23.48:8080/test.jpg");}        }

Layout file As long as a imageview is not written separately, directly look at the Cache tool class:

Import Android.graphics.bitmap;import android.util.log;import android.widget.imageview;/** * Created by Huang on 2016/ 12/3.    */public class Cacheutils {private static final String TAG = "Cacheutils";    Private Memorycacheutils mmemorycacheutils;    Private Localcacheutils mlocalcacheutils;    Private Netcacheutils mnetcacheutils;        Public Cacheutils () {mmemorycacheutils = new memorycacheutils ();        Mlocalcacheutils = new Localcacheutils ();    Mnetcacheutils = new Netcacheutils (mmemorycacheutils, mlocalcacheutils); } public void Diaplay (ImageView ImageView, String URL) {//Memory cache life cycle with caller Bitmap Bitmap = Mmemorycacheut        Ils.getbitmaptomemory (URL);            if (bitmap! = null) {Imageview.setimagebitmap (bitmap);            LOG.I (TAG, "diaplay:221111111111");        Return        }//Local cache bitmap = Localcacheutils.getbitmaptoloacl (URL);            if (bitmap! = null) {LOG.I (TAG, "diaplay:1111111"); ImagEview.setimagebitmap (bitmap);            Mmemorycacheutils.putbitmaptomemory (bitmap, URL);        Return    }//Network cache mnetcacheutils.getbitmapfromnet (ImageView, URL); }}

Tool classes for memory caching

 import android.graphics.bitmap;import android.util.log;import android.util.lrucache;import static android.content.contentvalues.tag;/** * Created by Huang on 2016/12/3.    */public class Memorycacheutils {private lrucache<string, bitmap> Mmemorycache;        Public memorycacheutils () {int maxmemory = (int) runtime.getruntime (). MaxMemory ();        LOG.I (TAG, "memorycacheutils:" + maxmemory); Mmemorycache = new lrucache<string, bitmap> (MAXMEMORY/8) {@Override protected int sizeOf (St            Ring key, Bitmap value) {return value.getrowbytes () * Value.getheight ();    }        };        } public void Putbitmaptomemory (Bitmap Bitmap, String url) {log.i (TAG, "putbitmaptomemory:");    Mmemorycache.put (URL, bitmap);        } public Bitmap getbitmaptomemory (String url) {log.i (TAG, "getbitmaptomemory:");        Bitmap Bitmap = mmemorycache.get (URL);    return bitmap; }}

Tool classes for local cache (SD card):

Import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.environment;import Android.util.log;import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Static android.content.contentvalues.tag;/** * Created by Huang on 2016/12/3. */public class Localcacheutils {public static void Putbitmaptoloacl (Bitmap Bitmap, string url) {string encode        = Md5utils.encode (URL);        File File = new file (Environment.getexternalstoragedirectory (), encode);        LOG.I (TAG, "Putbitmaptoloacl:" + file.tostring ());        File parent = File.getparentfile ();        if (!parent.exists ()) {parent.mkdirs ();        } try {bitmap.compress (Bitmap.CompressFormat.JPEG, +, new FileOutputStream (file));        } catch (FileNotFoundException e) {e.printstacktrace (); }} public static Bitmap getbitmaptoloacl (string url) {String encode = Md5utilS.encode (URL);        File File = new file (Environment.getexternalstoragedirectory (), encode);            if (file.exists ()) {Bitmapfactory.options opts = new Bitmapfactory.options ();            Opts.insamplesize = 3;                try {Bitmap Bitmap = Bitmapfactory.decodestream (new FileInputStream (file), NULL, opts);            return bitmap;                } catch (FileNotFoundException e) {e.printstacktrace ();            return null;    }} return null; }}

Tool classes for network caching:

Import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.asynctask;import Android.widget.imageview;import Java.io.ioexception;import Java.io.inputstream;import java.net.HttpURLConnection; Import java.net.url;/** * Created by Huang on 2016/12/3.    */public class Netcacheutils {private Memorycacheutils mmemorycacheutils;    Private Localcacheutils mlocalcacheutils; Public Netcacheutils (Memorycacheutils mmemorycacheutils, localcacheutils mlocalcacheutils) {this.mLocalCacheUtils        = Mlocalcacheutils;    This.mmemorycacheutils = mmemorycacheutils;        } public void Getbitmapfromnet (ImageView ImageView, String url) {imageview.settag (URL);        Bitmaptask task = new Bitmaptask ();    Task.execute (ImageView, URL);        } class Bitmaptask extends Asynctask<object, Void, bitmap> {private httpurlconnection urlconnection;        Private ImageView ImageView;        Private String URL; @Override protected void onPostExecute (Bitmap Bitmap) {if (Bitmap! = null) {if (Url.equals (Imageview.gettag ())) {                    Imageview.setimagebitmap (bitmap);                    System.out.print ("OnPostExecute");                    Mlocalcacheutils.putbitmaptoloacl (bitmap, URL);                Mmemorycacheutils.putbitmaptomemory (bitmap, URL); }}} @Override protected Bitmap doinbackground (object[] params) {ImageView =            (ImageView) params[0];            url = (String) params[1];            Bitmap Bitmap = downloadfromnet (URL);        return bitmap; } private Bitmap downloadfromnet (String url) {try {urlconnection = (httpurlconnection)                New URL (URL). OpenConnection ();                Urlconnection.setconnecttimeout (5000);                Urlconnection.setrequestmethod ("GET");                int responsecode = Urlconnection.getresponsecode (); if (Responsecode = =) {InputStream InputStream = Urlconnection.getinputstream ();                    Bitmapfactory.options opts = new Bitmapfactory.options ();                    Opts.insamplesize = 2;                    Bitmap Bitmap = Bitmapfactory.decodestream (InputStream, NULL, opts);                return bitmap;                }} catch (IOException e) {e.printstacktrace ();            return null;            } finally {Urlconnection.disconnect ();        } return null; }    }}

Md5utils tool classes used in the local cache:

Import java.security.messagedigest;/** * Created by Huang on 2016/12/3. */public class Md5utils {public    static string encode (string pwd) {        try {            MessageDigest digest = messagedigest . getinstance ("MD5");            byte[] bs = Digest.digest (Pwd.getbytes ());            StringBuilder sb = new StringBuilder ();            for (byte b:bs) {                int number = b & 0xFF;                String str = integer.tohexstring (number);                if (str.length () = = 1) {                    sb.append ("0");                }                Sb.append (number);            }            return sb.tostring ();        } catch (Exception e) {            e.printstacktrace ();            return null;}}    }

Finally, don't forget to add permissions:

    <uses-permission android:name= "Android.permission.INTERNET"/>    <uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/>    <uses-permission android:name=" android.permission.READ_ External_storage "/>

About level three cache in Android

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.