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

Android OOM 深度解析:記憶體洩漏、Bitmap 最佳化與 LruCache

編輯:關於 Android 程式設計

OOM 是什麼

OOM 全名為 OutOfMemoryError,代表應用程式嘗試配置記憶體時,可用空間不足。在 Android 中,OOM 常與記憶體洩漏、圖片載入過多、物件重複建立等因素有關。

常見 OOM 原因

資源物件未關閉

Cursor、InputStream、OutputStream、Bitmap 等資源若使用後未釋放,可能造成記憶體持續占用。建議在 finally 區塊中關閉串流,或在 Activity 結束時回收不再使用的資源。

非靜態內部類持有外部 Activity 參考

非靜態內部類會隱式持有外部類別參考。若內部類生命週期長於 Activity,例如 Handler、AsyncTask 或執行緒,就可能延遲 Activity 回收,造成記憶體洩漏。

Context 使用不當

Activity 的 Context 生命週期較短,不適合被長時間保存。若非必要,可優先使用 Application Context。若需要與 Activity 生命週期綁定,則應避免靜態變數或長效快取持有 Activity。

圖片資源過大

Bitmap 是 Android 記憶體消耗的大宗。載入高解析度圖片前,若未進行縮放或壓縮,很容易造成 OOM。

降低 Bitmap 記憶體占用的方法

常用方式包括設定 inSampleSize 縮放比例,以及選擇合適的解碼格式。載入圖片前,可先透過 inJustDecodeBounds 讀取圖片尺寸,再決定是否縮放。

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.drawable.sample, options);

int imageHeight = options.outHeight;
int imageWidth = options.outWidth;

取得原始尺寸後,可依目標顯示大小計算 inSampleSize。

public static int calculateInSampleSize(
        BitmapFactory.Options options,
        int reqWidth,
        int reqHeight) {

    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight) {
        final int heightRatio = Math.round((float) height / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);
        inSampleSize = heightRatio;
    }

    return inSampleSize;
}

第二次解析時,將 inJustDecodeBounds 設為 false,並套用計算後的 inSampleSize,即可得到縮放後的 Bitmap。

public static Bitmap decodeSampledBitmapFromResource(
        Resources res,
        int resId,
        int reqWidth,
        int reqHeight) {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeResource(res, resId, options);
}

使用 LruCache 快取圖片

在 ListView、GridView 或 ViewPager 等大量使用圖片的畫面中,LruCache 能有效減少重複載入。它會保存最近使用的物件,並在快取接近上限時移除最久未使用的項目。

private LruCache memoryCache;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    int cacheSize = maxMemory / 8;

    memoryCache = new LruCache(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getByteCount() / 1024;
        }
    };
}

快取大小不宜無限擴大。通常可從可用記憶體的一定比例開始嘗試,再依實際效能與 OOM 狀況調整。

避免記憶體洩漏的實務建議

  • Activity 內的 Handler 應在 onDestroy 中移除延遲訊息。
  • 內部類若需存活較久,建議改為靜態內部類並搭配 WeakReference。
  • 非必要時使用 Application Context,而非 Activity Context。
  • ListView 與 GridView 應使用 ViewHolder 與 convertView 重用機制。
  • 避免在 onDraw 等高頻方法中建立新物件。
  • 大量字串拼接時,可考慮使用 StringBuilder。

小結

OOM 並非單一原因造成,而是記憶體管理、資源釋放與圖片處理等多重因素綜合的結果。若能掌握 Bitmap 壓縮、快取策略與生命週期管理,就能大幅降低 Android 應用發生 OOM 的機率。

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