Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 資訊

Android 批量加載圖片的 OOM 排查與優化實錄

編輯:Android 資訊

一、問題從哪裡來

一個好用的 App 離不開精緻的圖片,所以圖片加載是 Android 開發中躲不開的一環。處理不當,OOM 就會找上門。本文把場景、原因和解法一次講清楚。

加載圖片引發 OOM 的場景大致就三種:

1、單張圖片過大

2、一次加載的圖片過多

3、以上兩種兼而有之

根本原因,官方文檔裡其實寫得很明白:

1、移動設備會限制每個 App 可用的內存,最小僅 16M,部分設備會分配得更多(24M、32M、64M 不等),總之存在上限。

2、Android 中的圖片以位圖形式載入內存,2.3 之後默認使用 ARGB_8888,每個像素佔 4 個字節,加載大圖自然極易撐爆內存。

二、先解決「大圖」

實際項目裡展示圖片時,受屏幕尺寸和佈局限制,我們通常不需要加載原始大圖,按比例采樣縮放即可。這樣既省內存,視覺上也不失真。

1. 只解碼尺寸,不載入像素

用到 BitmapFactory 的 decode 系列方法配合 BitmapFactory.Options,關鍵是把 inJustDecodeBounds 設為 true:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);

2. 計算縮放比例

public 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 || width > reqWidth) {
        if (width > height) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        } else {
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }
    }
    return inSampleSize;
}

3. 按比例真正加載

options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(path, options);

相比加載原圖,這樣能省下大量內存:

三、批量加載大圖

第一步仍然是根據界面控件尺寸確定縮放比例。下面以 GridView 加載本地圖片為例。

1. 讀取外部存儲中的所有圖片路徑

private void loadPhotoPaths() {
    Cursor cursor = getContentResolver().query(
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
    while (cursor.moveToNext()) {
        String path = cursor.getString(cursor.getColumnIndex(MediaColumns.DATA));
        paths.add(path);
    }
    cursor.close();
}

2. 在 Adapter 中顯示

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    if (convertView == null) {
        convertView = LayoutInflater.from(mContext).inflate(R.layout.grid_item_layout, null);
        holder = new ViewHolder();
        holder.photo = (ImageView) convertView.findViewById(R.id.photo);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    final String path = this.paths.get(position);
    holder.photo.setImageBitmap(imageLoader.getBitmapFromCache(path));
    return convertView;
}

3. 把加載搬到子線程

照這樣寫,程序一跑起來就卡在那裡半天沒反應——因為所有圖片都在主線程加載。給 ImageLoader 加一個線程池來管理下載線程:

private ExecutorService executor;

private ImageLoader(Context mContxt) {
    super();
    executor = Executors.newFixedThreadPool(3);
}

/** 異步加載圖片,帶回調監聽 */
public void loadImage(final ImageView view, final String path,
                      final int reqWidth, final int reqHeight,
                      final onBitmapLoadedListener callback) {
    final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Bitmap bitmap = (Bitmap) msg.obj;
                    callback.displayImage(view, bitmap);
                    break;
                default: break;
            }
        }
    };

    executor.execute(new Runnable() {
        @Override
        public void run() {
            Bitmap bitmap = loadBitmapInBackground(path, reqWidth, reqHeight);
            putBitmapInMemey(path, bitmap);
            Message msg = mHandler.obtainMessage(1);
            msg.obj = bitmap;
            mHandler.sendMessage(msg);
        }
    });
}

改造之後體驗明顯改善:

但還有兩個不容忽視的問題:

1、圖片錯位顯示

2、滑動過快時圖片加載跟不上

原因不難分析:一是 Adapter 複用 item 導致的 tag 錯亂,二是線程池裡堆積了過多無用任務。稍作修改即可:

Adapter 中——先設占位圖,把路徑寫進 tag,回調裡比對 tag 再更新:

holder.photo.setImageResource(R.drawable.ic_launcher);
holder.photo.setTag(path);
imageLoader.loadImage(holder.photo, path, DensityUtil.dip2px(80), DensityUtil.dip2px(80),
        new onBitmapLoadedListener() {
            @Override
            public void displayImage(ImageView view, Bitmap bitmap) {
                String imagePath = view.getTag().toString();
                if (imagePath.equals(path)) {
                    view.setImageBitmap(bitmap);
                }
            }
        });

ImageLoader 中——執行任務前先確認請求仍然有效:

executor.execute(new Runnable() {
    @Override
    public void run() {
        String key = view.getTag().toString();
        if (key.equals(path)) {
            Bitmap bitmap = loadBitmapInBackground(path, reqWidth, reqHeight);
            putBitmapInMemey(path, bitmap);
            Message msg = mHandler.obtainMessage(1);
            msg.obj = bitmap;
            mHandler.sendMessage(msg);
        }
    }
});

4. 加上緩存

想進一步優化,就該上緩存了。緩存分內存與磁盤兩層,本文示例加載的是本地圖片,因此只做了內存緩存。用 LruCache 承接,容量取應用內存的八分之一:

private ImageLoader(Context mContxt) {
    super();
    executor = Executors.newFixedThreadPool(3);

    // 取應用的八分之一作為圖片緩存
    ActivityManager am = (ActivityManager) mContxt.getSystemService(Context.ACTIVITY_SERVICE);
    int maxSize = am.getMemoryClass() * 1024 * 1024 / 8;
    mCache = new LruCache<String, Bitmap>(maxSize) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    };
}

public void putBitmapInMemey(String path, Bitmap bitmap) {
    if (path == null || bitmap == null) return;
    if (getBitmapFromCache(path) == null) {
        this.mCache.put(path, bitmap);
    }
}

public Bitmap getBitmapFromCache(String path) {
    return mCache.get(path);
}

之後在 loadImage 異步加載之前先查一次內存緩存,命中就直接返回。

四、小結

解決加載圖片 OOM,歸根結底是三件事:

1、不要加載原始大圖,按顯示控件尺寸做比例縮放後加載縮略圖。

2、不要在主線程加載圖片。在 ListView、GridView 中使用異步加載時,務必處理好圖片錯位與無效任務問題。

3、善用緩存,根據實際場景決定是否使用雙緩存以及緩存容量。

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