在上个章节《如何缓存你的Bitmap》中,说明了Bitmap对象的缓存与回收。本章来说Bitmap对象内存的管理,由于Adroid版本的差异,所以bitmap的内存管理方式有所不同。
先来简单说下Android系统各个版本管理Bitmap内存的差异,看看管理Bitmap的进化史。
Android2.2及以下:当垃圾回收器回收时线程停止,导致渲染延迟。Android2.3以后增加了concurrent垃圾回收器,意味着不再引用的Bitmap对象能够立即回收。
Android2.3.3及以下:Bitmap的像素数据时保持在native内存中的,而Bitmap对象本身保存在Dalvik head 中。在native内存中的像素信息的回收并不是按照常规回收,这使得对内存的把控变难,容易引起OOM。Android3.0开始Bitmap的像素数据也存储在Dalvik head中了。
接下来讲述在不同Android版本中如何优化管理Bitmap内存。
在Android2.3.3中管理Bitmap内存
在Android2.3.3及以下中,推荐使用recycle()方法释放内存。但是要十分谨慎:你要确保使用recycle()方法的Bitmap对象不再使用,如果你使用recycle()释放了Bitmap,然后又尝试绘制这个Bitmap,你就会得到一个“Canvas:trying to use a recycled bitmap”的异常。
下面给一个例子:什么时候调用recycle()。使用相关计数(使用两个变量:mDisplayRefCount和mCacheRefCount)来跟踪bitmap对象当前是否在显示或在缓存。bitmap回收满足两个条件:
mDisplayRefCount和mCacheRefCount同时为0.
bitmap不为null,切没有回收。
private int mCacheRefCount = 0; private int mDisplayRefCount = 0; ... // Notify the drawable that the displayed state has changed. // Keep a count to determine when the drawable is no longer displayed. public void setIsDisplayed(boolean isDisplayed) { synchronized (this) { if (isDisplayed) { mDisplayRefCount++; mHasBeenDisplayed = true; } else { mDisplayRefCount--; } } // Check to see if recycle() can be called. checkState(); } // Notify the drawable that the cache state has changed. // Keep a count to determine when the drawable is no longer being cached. public void setIsCached(boolean isCached) { synchronized (this) { if (isCached) { mCacheRefCount++; } else { mCacheRefCount--; } } // Check to see if recycle() can be called. checkState(); } private synchronized void checkState() { // If the drawable cache and display ref counts = 0, and this drawable // has been displayed, then recycle. if (mCacheRefCount <= 0 && mDisplayRefCount <= 0 && mHasBeenDisplayed && hasValidBitmap()) { getBitmap().recycle(); } } private synchronized boolean hasValidBitmap() { Bitmap bitmap = getBitmap(); return bitmap != null && !bitmap.isRecycled(); }
在Android3.0及以上管理Bitmap内存
在Android3.0中引入BitmapFactory.Options.inBitmap这个变量,如果这个变量被设置,便可以尝试使用已经存在的Bitmap加载内容,这就意味着bitmap的内存能够重用,从而提高显示速度,减少每次分配和回收吞吐过程。然而必须清楚使用inBitmap 的条件和限制,在Android4.4之前,只有相同大小的bitmap可以重用,在Android4.4以后只要小于inBitmap的都可以使用。
保存一份bitmap内存
下面例子的代码片段演示如何使用inBitmap来重复利用bitmap的内存。使用LruCache来缓存bitmap,当bitmap从缓存LruCache中移除时我们再将bitmap的内存设置到inBitmap使用软引用保存,以便后续可能的重复利用。
Set<SoftReference<Bitmap>> mReusableBitmaps; private LruCache<String, BitmapDrawable> mMemoryCache; // If you're running on Honeycomb or newer, create a // synchronized HashSet of references to reusable bitmaps. if (Utils.hasHoneycomb()) { mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>()); } mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) { // Notify the removed entry that is no longer being cached. @Override protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue, BitmapDrawable newValue) { if (RecyclingBitmapDrawable.class.isInstance(oldValue)) { // The removed entry is a recycling drawable, so notify it // that it has been removed from the memory cache. ((RecyclingBitmapDrawable) oldValue).setIsCached(false); } else { // The removed entry is a standard BitmapDrawable. if (Utils.hasHoneycomb()) { // We're running on Honeycomb or later, so add the bitmap // to a SoftReference set for possible use with inBitmap later. mReusableBitmaps.add (new SoftReference<Bitmap>(oldValue.getBitmap())); } } } .... }
使用存在的bitmap内存decode
先判断版本环境,例如:
public static Bitmap decodeSampledBitmapFromFile(String filename, int reqWidth, int reqHeight, ImageCache cache) { final BitmapFactory.Options options = new BitmapFactory.Options(); ... BitmapFactory.decodeFile(filename, options); ... // If we're running on Honeycomb or newer, try to use inBitmap. if (Utils.hasHoneycomb()) { addInBitmapOptions(options, cache); } ... return BitmapFactory.decodeFile(filename, options); }
addInBitmapOptions(),查询有无存在的bitmap内存可以设置到inBitmap。代码实现片段:
private static void addInBitmapOptions(BitmapFactory.Options options, ImageCache cache) { // inBitmap only works with mutable bitmaps, so force the decoder to // return mutable bitmaps. options.inMutable = true; if (cache != null) { // Try to find a bitmap to use for inBitmap. Bitmap inBitmap = cache.getBitmapFromReusableSet(options); if (inBitmap != null) { // If a suitable bitmap has been found, set it as the value of // inBitmap. options.inBitmap = inBitmap; } } } // This method iterates through the reusable bitmaps, looking for one // to use for inBitmap: protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) { Bitmap bitmap = null; if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) { synchronized (mReusableBitmaps) { final Iterator<SoftReference<Bitmap>> iterator = mReusableBitmaps.iterator(); Bitmap item; while (iterator.hasNext()) { item = iterator.next().get(); if (null != item && item.isMutable()) { // Check to see it the item can be used for inBitmap. if (canUseForInBitmap(item, options)) { bitmap = item; // Remove from reusable set so it can't be used again. iterator.remove(); break; } } else { // Remove from the set if the reference has been cleared. iterator.remove(); } } } } return bitmap; }
最后,下面这个方法用来判断候选bitmap内存大小是否满足inBitmap的要求:
static boolean canUseForInBitmap( Bitmap candidate, BitmapFactory.Options targetOptions) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // From Android 4.4 (KitKat) onward we can re-use if the byte size of // the new bitmap is smaller than the reusable bitmap candidate // allocation byte count. int width = targetOptions.outWidth / targetOptions.inSampleSize; int height = targetOptions.outHeight / targetOptions.inSampleSize; int byteCount = width * height * getBytesPerPixel(candidate.getConfig()); return byteCount <= candidate.getAllocationByteCount(); } // On earlier versions, the dimensions must match exactly and the inSampleSize must be 1 return candidate.getWidth() == targetOptions.outWidth && candidate.getHeight() == targetOptions.outHeight && targetOptions.inSampleSize == 1; } /** * A helper function to return the byte usage per pixel of a bitmap based on its configuration. */ static int getBytesPerPixel(Config config) { if (config == Config.ARGB_8888) { return 4; } else if (config == Config.RGB_565) { return 2; } else if (config == Config.ARGB_4444) { return 2; } else if (config == Config.ALPHA_8) { return 1; } return 1; }