(八)Bitmap内存管理

使用inBitmap结合LruCache来优化Bitmap的内存使用

Posted by chchaooo on April 16, 2018

Bitmap内存管理

除了在CachingBitmaps中描述的几个措施之外,你还可以做一些明确的事情来促进垃圾回收和位图的重用。Android目标版本决定了我们将推荐使用什么策略。BitmapFun这个示例app包含了这样一个类,这个类向你展示了怎样设计你的app,才能在android的不同版本之间高效率的工作。

为了给这节课打好基础, 先来看看Android关于Bitmap内存管理的进化:

  • 在Android2.2或更低的版本中,当发生垃圾回收时,你应用的线程都会暂停执行。这会导致延迟,降低程序性能。Android2.3增加了并发的垃圾回收机制,这意味着当图片对象不再被引用时所占用的内存空间立即就会被回收。
  • 在Android2.3.3或更低版本中,图片的像素数据是存储在Native内存中,它和Bitmap对象本身是分开来的,Bitmap对象本身是存储在Java虚拟机堆内存中。Android3.0之后,Bitmap像素数据和它本身都存储在Java虚拟机的堆内存中。

下面的部分介绍了对不同的Android版本中的Bitmap内存管理的优化

Android2.3或更低版本中对Bitmap内存的管理

在Android2.3或更低版本中,推荐使用recycle()方法。如果在你的应用中需要显示大量的图片,那么你的应用很有可能出现OutOfMemoryError 的错误。调用 recycle() 方法能让应用尽可能快的回收内存资源。

警告:只有当你确定不会再使用这张Bitmap图片时才应该调用recycle()方法。如果你调用recycle(),随后就尝试去画这张图,你将会得到”Canvas: trying to use a recycled bitmap” 的错误 。

下面的程序片段是给出了一个调用recycle() 方法的示例,它使用引用计数(mDisplayRefCount and 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属性。 如果设置了这个选项,那么在加载图片的时候,使用了Options对象作为参数的decode方法会试图重用已存在的Bitmap。这意味着Bitmap的内存资源被重用了,从而使得程序性能得到提高,并且省去了这份内存的分配和回收工作。下面是使用inBitmap 属性的一些说明和注意点:

  • 要进行重用的Bitmap的大小必须要跟源图片大小一致(确保两者使用的内存大小一样),而且图片必须是PNG或JPEG格式(可以是资源,也可以是二进制流数据).
  • 如果源图片设置了inPreferredConfig 配置项,那么要进行重用的Bitmap也设置此项.
  • 你应该总是使用decode方法返回的Bitmap,因为你不能保证重用的Bitmap是否可靠(比如,上面提到的大小有可能不匹配)

缓存暂时不用的bitmap对象

下面的程序片段演示了 在示例应用中一个已存在的bitmap是如何存储以备之后使用的。 当应用运行在Android3.0或更高版本上,当一张Bitmap从LruCache退出时,Bitmap的软引用会被保存在一个HashSet中 ,可能稍后会被inBitmap 使用。

HashSet<SoftReference<Bitmap>> mReusableBitmaps;  
private LruCache<String, BitmapDrawable> mMemoryCache;  
  
// If you're running on Honeycomb or newer, create  
// a HashSet of references to reusable bitmaps.  
if (Utils.hasHoneycomb()) {  
    mReusableBitmaps = 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对象

在运行的app中,decoder 方法会去检查是否有一张已经存在的Bitmap可以使用,例如:

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() 方法在下面定义了。它会去查找inBitmap是否设置了一张已经存在的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()) {  
        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;  
}  

最后,这个方法用来判断一张候选图片是否满足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;
}