Android bitmaps Cache

Source: Internet
Author: User

Android Development, Bitmap is the culprit that caused the memory leak, about bitmap loading, caching policy, the official has given a very detailed method:

Cached Memory Cache:

The cached policy is to use the allocated memory of the application to take out the appropriate portion of the cache using the LRUCache algorithm. about how much memory to use to cache the picture, this depends on the different pictures, models and screen resolution for the comprehensive consideration, such as for the same picture, the Galaxy nexus than the Nexus S need more memory.

To cache the sample code with LRUCache:

Private lrucache<string, bitmap> Mmemorycache, @Overrideprotected void OnCreate (Bundle savedinstancestate) {... Get Max available VM memory, exceeding this amount would throw AN//OutOfMemory exception.    Stored in kilobytes as LruCache takes a//int in its constructor.    Final int maxmemory = (int) (Runtime.getruntime (). MaxMemory ()/1024);    Use 1/8th of the available memory for this memory cache.    Final int cacheSize = MAXMEMORY/8; Mmemorycache = new lrucache<string, bitmap> (cacheSize) {@Override protected int sizeOf (String key, Bi            TMap bitmap) {//The cache size is measured in kilobytes rather than//number of items.        return Bitmap.getbytecount ()/1024;    }    }; ...} public void Addbitmaptomemorycache (String key, Bitmap Bitmap) {if (Getbitmapfrommemcache (key) = = null) {Mmemor    Ycache.put (key, bitmap); }}public Bitmap Getbitmapfrommemcache (String key) {return mmemoryCache.get (key);} 

  

When loading the picture, if there is a picture in the cache, it is loaded directly from the cache, no one background thread to perform the loading of the picture:

public void LoadBitmap (int resId, ImageView ImageView) {    final String ImageKey = string.valueof (resId);    Final Bitmap Bitmap = Getbitmapfrommemcache (ImageKey);    if (bitmap! = null) {        mimageview.setimagebitmap (bitmap);    } else {        Mimageview.setimageresource ( R.drawable.image_placeholder);        Bitmapworkertask task = new Bitmapworkertask (mimageview);        Task.execute (resId);    }}

  

Class Bitmapworkertask extends Asynctask<integer, Void, bitmap> {    ...    Decode image in background.    @Override    protected Bitmap doinbackground (Integer ... params) {        final Bitmap Bitmap = Decodesampledbitmapfromresource (                getresources (), Params[0], (+));        Addbitmaptomemorycache (String.valueof (Params[0]), bitmap);        return bitmap;    }    ...}

  

Cached disk cache:

For the picture is small, the number of pictures is less, has a faster load efficiency requirements, with memory cache is undoubtedly the best choice, but when for, pictures more scenes, such as the Gridview, the ListView loading a large number of pictures, memory is unbearable, at this time, You need to use external storage devices such as disks for caching.

In fact, if the picture is switched more frequently, then the ContentProvider Cliff is a good choice, such as Image Gallery application.

The official sample code for using disk cache is as follows:

Private Disklrucache mdisklrucache;private Final Object mdiskcachelock = new Object ();p rivate boolean mdiskcachestarting = true;private static final int disk_cache_size = 1024 * 1024 * 10; 10MBprivate static final String Disk_cache_subdir = "thumbnails"; @Overrideprotected void OnCreate (Bundle  Savedinstancestate) {...//Initialize memory Cache ...//Initialize disk cache on background thread File    Cachedir = Getdiskcachedir (this, disk_cache_subdir);    New Initdiskcachetask (). Execute (CACHEDIR); ...} Class Initdiskcachetask extends Asynctask<file, void, void> {@Override protected void Doinbackground (File ...            params) {synchronized (mdiskcachelock) {File cachedir = params[0];            Mdisklrucache = Disklrucache.open (Cachedir, disk_cache_size); Mdiskcachestarting = false; Finished initialization mdiskcachelock.notifyall ();    Wake any waiting threads} return null; }}class Bitmapworkertask EXTends Asynctask<integer, Void, bitmap> {...//Decode image in background. @Override protected Bitmap doinbackground (Integer ... params) {final String ImageKey = string.valueof (Params[0])        ;        Check disk cache in background thread Bitmap Bitmap = Getbitmapfromdiskcache (ImageKey); if (bitmap = = null) {//not found in disk cache//Process as normal final bitmap bitmap = Decodesa        Mpledbitmapfromresource (Getresources (), params[0], 100, 100));        }//ADD final bitmap to caches Addbitmaptocache (ImageKey, bitmap);    return bitmap; }    ...} public void Addbitmaptocache (String key, Bitmap Bitmap) {//ADD to memory cache as before if (Getbitmapfrommemcache    (key) = = null) {Mmemorycache.put (key, bitmap); }//Also add to disk cache synchronized (Mdiskcachelock) {if (Mdisklrucache! = null && Mdisklrucach E.get (key) = = null) {MdisklrucaChe.put (key, bitmap); }}}public Bitmap Getbitmapfromdiskcache (String key) {synchronized (Mdiskcachelock) {//Wait while disk CAC He is started from background thread while (mdiskcachestarting) {try {Mdiskcachelock.wa            It ();         } catch (Interruptedexception e) {}} if (Mdisklrucache! = null) {return mdisklrucache.get (key); }} return null;} Creates a unique subdirectory of the designated app cache directory. Tries to use external//but if not mounted, falls back on internal storage.public static File Getdiskcachedir (Context cont    Ext, String uniqueName) {//Check If media is mounted or storage are built-in, if so, try and use external cache dir Otherwise use internal cache dir final String CachePath = Environment.MEDIA_MOUNTED.equals (environment.g                    Etexternalstoragestate ()) | | !isexternalstorageremovable ()? Getexternalcachedir (context). GetPath (): Context.getcachedir (). GetPath (); return new File (CachePath + file.separator + uniqueName);}

  

The memory cache executes in the UI thread, and Disk cache is executed in the Backound thread.

When the screen rotates, or other configuration changes, such as the phone in, Pop-up dialog box, the activity is destroyed, reset, you need to save the previous cache;

For example, a code sample that saves a cache object in a fragment:

Private lrucache<string, bitmap> Mmemorycache, @Overrideprotected void OnCreate (Bundle savedinstancestate) {...    Retainfragment retainfragment = retainfragment.findorcreateretainfragment (Getfragmentmanager ());    Mmemorycache = Retainfragment.mretainedcache; if (Mmemorycache = = null) {Mmemorycache = new lrucache<string, bitmap> (cacheSize) {...//Initia    Lize cache here as usual} Retainfragment.mretainedcache = Mmemorycache; }    ...}    Class Retainfragment extends Fragment {private static final String TAG = "Retainfragment";    Public lrucache<string, bitmap> Mretainedcache; Public retainfragment () {} public static retainfragment findorcreateretainfragment (Fragmentmanager FM) {Retainf        Ragment fragment = (retainfragment) fm.findfragmentbytag (TAG);            if (fragment = = null) {fragment = new retainfragment ();        Fm.begintransaction (). Add (fragment, TAG). commit (); } RETurn fragment;        } @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);    Setretaininstance (TRUE); }}

  

From:http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#config-changes

Android bitmaps 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.