I have an app which operates a large quantity (~100) of bitmaps - i.e. 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 开发者_如何学Csee 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):
- 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.
- Use the Canvas' drawBitmap methods to draw the large-scale bitmaps smaller.
- 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.
- Use
recycle()
to flush out the memory cache beforeout 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
- You may use
inBitmap
field inBitmapFactory.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
精彩评论