简体   繁体   中英

Android bitmap caching

I have an app which operates a large quantity (~100) of bitmaps - ie music cover art. Bitmaps are used in two ways - as a large background and a small (50dip) icon. Does it make sense to preload and cache two sizes as separate bitmaps? I've implemented both approaches (use large bitmap as the icon | cache both sizes), but I can't see actual performance difference. What is the best practice for such situation?

There's no sense in caching both image sizes, it takes too much memory.

Best practices would be (to my humble opinion):

  1. Make sure your cache uses SoftReferences , this way you can make sure that you don't run out of memory, and can always load new bitmaps on the "expense" of losing old ones.
  2. Use the Canvas' drawBitmap methods to draw the large-scale bitmaps smaller.
  3. Make sure you guard against OutOfMemoryError , and notice that it's a subclass of Throwable, and not a subclass of Exception, so a catch(Exception e) clause will not catch it.

Personally, I would do my best to limit the number of Bitmaps I'm keeping around in memory. If the icon looks fine as a scaled down copy of the larger Bitmap, I'd favor that approach. This is probably a biased opinion because of my personal experience, but the biggest problems I've had in my experience with Android has been running out of memory when working with Bitmaps

Must not save both files, save the larger one.

Try to work on memory management of memory cache.

  1. Use recycle() to flush out the memory cache before out of memory exception occurs .

Internally this recycle() work on reference count mechanism which checks:

It uses reference counting (in the variables mDisplayRefCount and mCacheRefCount ) to track whether a bitmap is currently being displayed or in the cache. The code recycles the bitmap when these conditions are met:

  • The reference count for both mDisplayRefCount and mCacheRefCount is 0.
  • The bitmap is not null, and it hasn't been recycled yet.

Refer Implementation here

  1. You may use inBitmap field in BitmapFactory.Options class object to keep the bitmap for later use.

Where, a bitmap is evicted from the LruCache, a soft reference to the bitmap is placed in a HashSet, for possible reuse later with inBitmap:

Set<SoftReference<Bitmap>> mReusableBitmaps;

3. Using BitmapFactory.Options Class load large bitmap in small imageviews efficently. by calculating inSampleSize and providing it in options.inSampleSize field.

inSampleSize is a factor which determines level of lowering a large image into small imageview calculated via height and width in options field

You may refer here for implementation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM