萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android Bitmap 記憶體優化完整指南:回收、緩存、壓縮與 OOM 防護

圖片是 Android 應用最大記憶體消耗源。Dalvik/ART 預設堆上限僅 8-64MB(視裝置),輕易觸發 OutOfMemoryError (OOM)。本文系統整理 Bitmap 記憶體優化四大支柱。

1. 及時回收 Bitmap 原生記憶體

Bitmap 物件分 Java 堆(小)與 Native 堆(像素數據,大)。recycle() 釋放 Native 記憶體,GC 只能回收 Java 端。不再使用時必須主動呼叫。

if (bitmap != null && !bitmap.isRecycled()) {
    bitmap.recycle();   // 釋放 Native 像素記憶體
    bitmap = null;      // 斷開 Java 參考
}
System.gc(); // 建議 GC,非強制

時機: Activity onStop() / onDestroy()、View 脫離視窗、列表項目回收時。切記: recycle 後不可再用,否則拋 Canvas: trying to use a recycled bitmap。

2. 捕獲 OOM 避免 Crash

Bitmap bitmap = null;
try {
    bitmap = BitmapFactory.decodeFile(path);
} catch (OutOfMemoryError e) {
    Log.e("Bitmap", "OOM decoding " + path, e);
}
if (bitmap == null) return getDefaultBitmap(); // 降級策略

陷阱: OutOfMemoryError 是 Error 而非 Exception,catch (Exception e) 捕獲不到!必須寫 catch (OutOfMemoryError e)。

3. 緩存通用 Bitmap(記憶體 + 磁碟兩級)

  • 記憶體緩存: LruCache<String, Bitmap> 存放高頻圖片(如預設頭像、UI 圖標),避免重複解碼。
  • 磁碟緩存: DiskLruCache 儲存網路下載圖片,下次離線可用,節省流量。
  • Glide、Picasso、Coil 等成熟圖片庫已內建兩級緩存、生命週期感知、自動縮放,**強烈建議直接使用成熟庫,勿重造輪子**。

4. 解碼時壓縮圖片

大圖直接解碼極易 OOM。使用 BitmapFactory.Options.inSampleSize 縮放:

// 步驟 1:只解碼邊界,不分配像素記憶體
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, opts);
int srcW = opts.outWidth, srcH = opts.outHeight;

// 步驟 2:計算縮放比(目標寬高如 ImageView 實際尺寸)
int targetW = imageView.getWidth(), targetH = imageView.getHeight();
int inSampleSize = 1;
if (srcW > targetW || srcH > targetH) {
    inSampleSize = Math.max(srcW / targetW, srcH / targetH);
}

// 步驟 3:正式解碼
opts.inJustDecodeBounds = false;
opts.inSampleSize = inSampleSize;
opts.inPreferredConfig = Bitmap.Config.RGB_565; // 節省 50% 記憶體(無透明通道時)
Bitmap bitmap = BitmapFactory.decodeFile(path, opts);

進階:inBitmap 重用記憶體 (API 11-18)

舊版本可設 opts.inMutable = true; opts.inBitmap = reusableBitmap; 重用既有像素陣列。API 19+ 建議改用 BitmapPool(Glide 內建)。

實戰檢查清單

  1. 所有 decodeXxx 呼叫是否包裹 try-catch OOM?
  2. 列表/Grid 圖片是否使用 inSampleSize 縮略圖?
  3. 離開頁面/銷毀時是否 recycle() 大圖?
  4. 是否接入成熟圖片庫(Glide/Picasso/Coil)統一管理?
  5. 大量圖片頁面是否啟用 inPurgeable/inInputShareable (舊 API) 或 BitmapFactory.Options.inMutable?
copyright © 萬盛學電腦網 all rights reserved