Android Memory optimized memory cache

Source: Internet
Author: User

Objective:

The memory cache is described in the previous article, and the advantage of memory caching is that it is fast, but it has drawbacks:

    • Small space, memory cache can not be very large;
    • may be cleared when memory is tight;
    • When the application exits, it disappears and does not go offline;

Based on the disadvantages above, sometimes another kind of cache is needed, that is, the disk cache. Everyone should have used the news client, many have offline functions, the implementation of the function is the disk cache.

Disklrucache:

Most of the disk caches used in Android are based on the Disklrucache implementation, how to use them?

    • Create a disk Cache object:

public static Disklrucache open (File directory, int appversion, int valuecount, long maxSize);
The Open () method receives four parameters, the first parameter is the cached file address of the data, the second parameter is the version number of the current application, the third parameter is the same key can correspond to how many cache files, generally is 1, the fourth parameter is the maximum number of bytes of data can be cached, 10M?

    • To get the cache path:
Creates a unique subdirectory of the designated app cache directory. Tries to using external//but if not mounted, falls back on internal storage.//Create disk cache file, preferred sdcard, if sdcard is not mounted or not SDcard get app Default cache directory public static File Getdiskcachedir (context context, String UniqueName) {    //Check If media is mounted or sto  Rage is built-in, if so, try and use external cache dir    //otherwise use internal cache dir    final String CachePath =            Environment.MEDIA_MOUNTED.equals (environment.getexternalstoragestate ()) | |                    ! Isexternalstorageremovable ()? Getexternalcachedir (context). GetPath ():                            Context.getcachedir (). GetPath ();    return new File (CachePath + file.separator + uniqueName);}
    • Get software version number:
public int Getappversion (context context) {try {packageinfo packageinfo = Context.getpackagemanager (). Getpackageinfo ( Context.getpackagename (), 0); return packageinfo.versioncode;} catch (Namenotfoundexception e) {e.printstacktrace ();} return 1;}
    • The complete code is as follows:
Disklrucache Mdisklrucache = null;try {File Cachedir = Getdiskcachedir (Context, "thumbnails"); if (!cachedir.exists ()) { Cachedir.mkdirs ();} Mdisklrucache = Disklrucache.open (Cachedir, getappversion (context), 1, 10 * 1024 * 1024);} catch (IOException e) {e.printstacktrace ();}
    • Specifically how to use the disk cache created above is as follows:
Add cache public void Addbitmaptocache (String key, Bitmap Bitmap) {    //Add to memory cache as before, put the cache in the    Tbitmapfrommemcache (key) = = null) {        mmemorycache.put (key, bitmap);    }    Also add to disk cache, put the cache into the disk buffer    synchronized (mdiskcachelock) {        if (mdisklrucache! = null && Mdisklruc Ache.get (key) = = null) {            mdisklrucache.put (key, bitmap);}}}    Get Cache public Bitmap Getbitmapfromdiskcache (String key) {    synchronized (mdiskcachelock) {        //Wait while disk Cache is started from background the thread        while (mdiskcachestarting) {            try {                mdiskcachelock.wait ();            } catch (Interruptedexception e) {}        }        if (Mdisklrucache! = null) {            return mdisklrucache.get (key);        }    }    return null;}
Summarize:

The above is how the disk cache is created and used. In practice, the memory cache and the disk cache are used together, typically reading data from the in-memory cache, if no more is read from the disk cache. Personal level is limited, what questions can leave a message, the best is to add my public number:coder_online, I can timely see your message and give you an answer.

Want to get more original articles in the first time, please pay attention to the personal public platform: Programmer Interaction Alliance (Coder_online), sweep the QR code below or search number Coder_online can pay attention to, there are a lot of android,chromium, Linux, programming skills and other related articles waiting for you, we can also communicate online.


Android Memory optimized memory cache

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.