除了前面說的Bitmap緩存之外,還有一些事情我們可以做來使用好GC和Bitmap的重用. 對于不同的Android版本要做不同的處理,這樣才能達(dá)到高效使用Bitmap的效果,這是推薦的策略.
這里先介紹一些關(guān)于Android中Bitmap內(nèi)存管理的基礎(chǔ)知識鋪墊一下:
- 在Android2.2(API 8)及以前,當(dāng)GC開始回收時,app的所有線程都將停止, 這就導(dǎo)致了延遲的產(chǎn)生,進(jìn)而影響體驗(yàn). Android2.3及之后就不會用這個問題了,因此增加了GC的并發(fā)處理,也就意味著Bitmap被清理之后app的可用空間會很快回收回來.
- Android2.3.3(API 10)及以前,Bitmap的圖片數(shù)據(jù)是保存在native memory上, 而Bitmap對象是保存在Dalvik的heap上,這樣這兩個就分離開了,就會導(dǎo)致內(nèi)存釋放不及時從而帶來潛在的OOM. 在Android 3.0(API 11)之后這個問題就解決了,因?yàn)檫@兩個都被放在Dalvik的heap上.
下面介紹如何根據(jù)不同的Android版本來管理Bitmap的內(nèi)存.
Android2.3.3及以下
在這個版本范圍內(nèi),推薦使用recycle()方法, 該方法會盡快把Bitmap的內(nèi)存回收回來.
- 注意: 你只有在確定這個Bitmap不再使用的情況下才去調(diào)用recycle()方法. 不然如果你調(diào)用recycle()之后又要想去使用之前的Bitmap,會拋出一個異常:"Canvas: trying to use a recycled bitmap"
下面的代碼是Demo中RecyclingBitmapDrawable的一部分,其中mDisplayRefCount和mCacheRefCount這兩個變量用來記錄該Bitmap顯示和緩存情況,具體回收條件如下:
- mDisplayRefCount和mCacheRefCount的值都為0.
- Bitmap不為空.
完整代碼請參考官方demo,下面Reference帶下載地址.
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();
}
Android 3.0及以上
Android 3.0(API 11)引入了 BitmapFactory.Options.inBitmap屬性.如果設(shè)置了該屬性, BitmapFactory帶有Options參數(shù)的decode相關(guān)方法會嘗試去重用已存在的Bitmap, 這就意味這Bitmap的內(nèi)存空間得到了重用, 就可以改善性能,減少內(nèi)存分配和回收.
但是使用inBitmap這個屬性有一些限制, 有一點(diǎn)比較特別的是在Android4.4以前(API 19),只有相同大小的Bitmap才可以重用,具體可以看inBitmap文檔.
下面看具體實(shí)例:
1. 保存Bitmap
下面是用一個HashSet來保存從LruCache中移除的Bitmap的軟引用.
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()));
}
}
}
....
}
2. 重用Bitmap
查找是否有可重用的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);
}
如果找到可用的就設(shè)置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;
}
查找時具體的匹配條件如下
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;
}