Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 高效顯示位圖:如何在不同版本上管理位圖內存

編輯:關於 Android 程式設計

本文翻譯整理自 Android 官方培訓文檔,主題是位圖內存的管理與優化。除了常規的加載與緩存策略外,還有一些細節能促進垃圾回收、實現位圖復用。最佳策略取決於你的目標 Android 版本,官方示例 BitmapFun 演示了如何在不同版本上高效工作。

在深入之前,先了解幾個關於 Android 如何管理位圖內存的重要背景:

在 Android 2.2 之前,垃圾回收發生時應用的線程會被整體暫停,從而帶來性能延遲。Android 2.3 引入了並發垃圾回收,意味著內存能在較短時間內被回收,位圖一旦不再被引用便可釋放。

在 Android 3.0 之前,位圖的像素數據存放在本地內存(native heap)中,與位圖對象本身(位於 Dalvik 堆)相互分離。這帶來一個問題:位於本地內存的像素數據不會隨對象一起被釋放,容易導致應用超出內存上限而崩潰。從 Android 3.0 開始,像素數據與位圖對象一同存入了 Dalvik 虛擬機堆,回收機制得以統一管理。

一、Android 2.3 之前的內存管理

在 2.3 之前,官方推薦使用 recycle() 方法。當應用展示大量位圖時,很可能遭遇 OutOfMemoryError,而 recycle() 能幫助應用盡快回收內存。

注意:只有在確保位圖不再使用時才能調用 recycle()。若在 recycle() 之後仍嘗試繪製該位圖,將拋出錯誤:「Canvas: trying to use a recycled bitmap」。

下面的示例展示了 recycle() 的典型用法,它採用引用計數的方式,追蹤位圖當前是處於「展示」還是「緩存」狀態,僅當兩個引用計數都歸零、且位圖有效尚未被回收時,才會真正回收:

private int mCacheRefCount = 0;
private int mDisplayRefCount = 0;

// 展示狀態變化時通知,並維護計數
public void setIsDisplayed(boolean isDisplayed) {
    synchronized (this) {
        if (isDisplayed) {
            mDisplayRefCount++;
            mHasBeenDisplayed = true;
        } else {
            mDisplayRefCount--;
        }
    }
    checkState();
}

// 緩存狀態變化時通知,並維護計數
public void setIsCached(boolean isCached) {
    synchronized (this) {
        if (isCached) {
            mCacheRefCount++;
        } else {
            mCacheRefCount--;
        }
    }
    checkState();
}

private synchronized void checkState() {
    // 展示與緩存計數均為 0,且曾被展示、位圖有效,則回收
    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 引入了 BitmapFactory.Options.inBitmap 屬性。若設置了該選項,解碼方法會嘗試復用一個已存在的位圖。這意味著位圖內存可被重用,既能改善性能,又能省去反覆申請與釋放內存的开銷。不過 inBitmap 的使用有一些限制:在 Android 4.4 之前,僅支持復用尺寸完全相同的位圖。

1. 保存位圖以備後用

下面的代碼演示了如何保存位圖以便稍後復用。當應用運行在 Android 3.0 及以上時,一旦位圖被 LruCache 移除,就會被一個軟引用(SoftReference)包裹並放入 HashSet,以備日後通過 inBitmap 再次使用:

Set> mReusableBitmaps;
private LruCache mMemoryCache;

if (Utils.hasHoneycomb()) {
    mReusableBitmaps =
        Collections.synchronizedSet(new HashSet>());
}

mMemoryCache = new LruCache(mCacheParams.memCacheSize) {
    @Override
    protected void entryRemoved(boolean evicted, String key,
                                BitmapDrawable oldValue, BitmapDrawable newValue) {
        if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
            ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
        } else if (Utils.hasHoneycomb()) {
            // 3.0 及以上:加入軟引用集合,供日後 inBitmap 復用
            mReusableBitmaps.add(new SoftReference(oldValue.getBitmap()));
        }
    }
    // ...
};

2. 使用已存在的位圖

在解碼前,先檢查是否有可復用的位圖:

public static Bitmap decodeSampledBitmapFromFile(
        String filename, int reqWidth, int reqHeight, ImageCache cache) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    // ... 設置 inJustDecodeBounds 等,先後兩次 decode
    BitmapFactory.decodeFile(filename, options);
    if (Utils.hasHoneycomb()) {
        addInBitmapOptions(options, cache);
    }
    return BitmapFactory.decodeFile(filename, options);
}

addInBitmapOptions() 的實現:

private static void addInBitmapOptions(
        BitmapFactory.Options options, ImageCache cache) {
    // inBitmap 僅對可變位圖生效,故強制解碼返回可變位圖
    options.inMutable = true;
    if (cache != null) {
        Bitmap inBitmap = cache.getBitmapFromReusableSet(options);
        if (inBitmap != null) {
            options.inBitmap = inBitmap;
        }
    }
}

// 遍歷可復用集合,尋找合適的位圖
protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) {
    Bitmap bitmap = null;
    if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) {
        synchronized (mReusableBitmaps) {
            final Iterator> iterator = mReusableBitmaps.iterator();
            Bitmap item;
            while (iterator.hasNext()) {
                item = iterator.next().get();
                if (null != item && item.isMutable()) {
                    if (canUseForInBitmap(item, options)) {
                        bitmap = item;
                        iterator.remove(); // 從集合移除,避免重複使用
                        break;
                    }
                } else {
                    iterator.remove(); // 引用已被回收則移除
                }
            }
        }
    }
    return bitmap;
}

最後,canUseForInBitmap 會判斷候選位圖是否滿足尺寸要求:

static boolean canUseForInBitmap(Bitmap candidate, BitmapFactory.Options targetOptions) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // 4.4 起:新位圖字節數小於等于候選位圖的分配字節數即可復用
        int width = targetOptions.outWidth / targetOptions.inSampleSize;
        int height = targetOptions.outHeight / targetOptions.inSampleSize;
        int byteCount = width * height * getBytesPerPixel(candidate.getConfig());
        return byteCount <= candidate.getAllocationByteCount();
    }
    // 早期版本:尺寸必須完全一致,且 inSampleSize 為 1
    return candidate.getWidth() == targetOptions.outWidth
        && candidate.getHeight() == targetOptions.outHeight
        && targetOptions.inSampleSize == 1;
}

// 根據配置返回每像素的位元組數
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;
}

可以看到,Android 4.4(KitKat)放寬了復用條件——只要新位圖的內存需求不超過候選位圖的分配大小即可復用;而在更早的版本上,則要求尺寸精確匹配且 inSampleSize 為 1。


總結來說,位圖內存管理需要根據目標版本採取不同策略:2.3 之前依靠 recycle() 主動回收並做好引用計數;3.0 之後則善用 inBitmap 復用機制,配合 LruCache 與軟引用集合,顯著降低內存分配帶來的開銷與 GC 壓力。掌握這些細節,才能在列表、瀑布流等大量加載圖片的場景下保持應用的流暢與穩定。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved