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

Android 非同步載入圖片的一種自製方案:AsyncImageLoader 剖析

編輯:關於 Android 程式設計

先誠實說明:這個方法我後來已經放棄了,實際使用時發現加載速度不理想(具體原因我沒有細究)。目前改用 Volley。之所以還是把它寫出來,是因為裡面有幾段處理大圖的思路值得記錄,也方便日後對照檢討。

整體結構

AsyncImageLoader 由幾個部分組成:一個 SoftReference 做的記憶體快取、一個 ThreadPoolExecutor 執行的下載隊列、一組本地檔案快取的路徑管理,以及負責縮放的 BitmapFactory 解碼邏輯。

package com.souya.seller.util.ex;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.Video.Thumbnails;
import android.content.Context;

public class AsyncImageLoader {

    private static final String TAG = "AsyncImageLoader";
    public static String CachePath = null;
    private static String ThumbnailPath = null;
    private static boolean _isInit = false;
    private static Context _ctx;

    // 佔位用的小圖,用來標記「正在加載中」
    private static Bitmap _empty = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565);

    private static HashMap<String, SoftReference<Bitmap>> imageCache =
            new HashMap<String, SoftReference<Bitmap>>();

    private static Queue<Runnable> queue = new Queue<Runnable>();

    // 線程池:最大 20 條,每次執行 1 條,空閒線程超時 300 秒
    private static ThreadPoolExecutor executor =
            new ThreadPoolExecutor(1, 20, 300, TimeUnit.SECONDS, queue);

    public final static AsyncImageLoader Instance = new AsyncImageLoader();

    public static void Init(final Context context) {
        CachePath = SellerApplication.getInstance().mAppCacheDir + "";
        ThumbnailPath = CachePath + "/thumbnails";
        if (!new File(ThumbnailPath).exists()) new File(ThumbnailPath).mkdirs();
        _ctx = context;
        _isInit = true;
    }
}

這裡有兩個設計意圖值得指出。第一,_empty 是一個 1x1 的佔位圖:拜訪快取時若發現某個 key 對應到 _empty,就代表「有人正在下載這張圖,請稍候」,這是避免同一個 URL 被重複請求的簡易手法。第二,用 SoftReference 而非 LruCache 包住 Bitmap,是為了在記憶體吃緊時讓 GC 自動回收,這在早期低記憶體的裝置上很常見,但後來的實務證明它並不可靠——GC 的時機與意願都不受控制,快取命中率往往低於預期,這也是 LruCache 後來成為標準做法的原因。

對外的主要接口

public static Drawable loadDrawable(final Context context, final String url,
        final ImageCallback imageCallback) {
    if (!_isInit) Init(context);
    final String key = url;

    synchronized (imageCache) {
        if (imageCache.containsKey(key)) {
            SoftReference<Bitmap> softReference = imageCache.get(key);
            Bitmap bmp = softReference.get();
            if (bmp != null && !bmp.isRecycled()) {
                if (bmp == _empty) {
                    bmp = bmp;   // 佔位中,落到下面重新排隊
                } else {
                    return new BitmapDrawable(bmp);   // 命中快取,直接回傳
                }
            }
        } else {
            imageCache.put(key, new SoftReference<Bitmap>(_empty));
        }
    }

    final Handler handler = new Handler() {
        public void handleMessage(Message message) {
            imageCallback.imageLoaded((Drawable) message.obj, url);
        }
    };

    executor.execute(new Runnable() {
        @Override
        public void run() {
            Bitmap bmp = loadImage(url);
            if (bmp != null) {
                synchronized (imageCache) {
                    if (imageCache.containsKey(key)) {
                        imageCache.put(key, new SoftReference<Bitmap>(bmp));
                        Message message = handler.obtainMessage(0, new BitmapDrawable(bmp));
                        handler.sendMessage(message);
                    } else {
                        if (!bmp.isRecycled()) bmp.recycle();
                        bmp = null;
                        System.gc();
                    }
                }
            }
        }
    });
    return null;
}

public interface ImageCallback {
    public void imageLoaded(Drawable imageDrawable, String imageUrl);
}

注意 Handler 是在呼叫端執行緒上建立的,因此回呼 imageLoaded 會回到主執行緒,可以直接更新 UI——這是這個設計能運作的前提。另外那個 if (bmp == _empty) { bmp = bmp; } 其實是個空操作,原意應該是「不做事、繼續往下排隊」,寫成這樣只是為了讓分支看起來對稱,實際上可以直接去掉 if 判斷。

核心: avoiding OOM 的解碼策略

這個類裡最有價值的部分,是 loadLocalImage 中處理大圖的方式。它的關鍵在於兩段式解碼:

private static Bitmap _loadLocalImage(String url, int width, int height) {
    try {
        if (!new File(url).exists()) return null;

        // 第一步:只讀尺寸,不載入像素
        BitmapFactory.Options op = new BitmapFactory.Options();
        op.inJustDecodeBounds = true;
        Uri uri = Uri.fromFile(new File(url));
        Bitmap pic = BitmapFactory.decodeStream(
                _ctx.getContentResolver().openInputStream(uri), null, op);

        int wRatio = (int) Math.ceil(op.outWidth  / (float) width);
        int hRatio = (int) Math.ceil(op.outHeight / (float) height);
        if (pic != null && !pic.isRecycled()) pic.recycle();

        // 第二步:寬高都超出目標才縮放,取比例較大者
        if (wRatio > 1 && hRatio > 1) {
            if (wRatio > hRatio) {
                op.inSampleSize = wRatio;
            } else {
                op.inSampleSize = hRatio;
            }
        }
        op.inJustDecodeBounds = false;   // 這裡一定要設回 false
        try {
            pic = BitmapFactory.decodeStream(
                    _ctx.getContentResolver().openInputStream(uri), null, op);
        } catch (OutOfMemoryError e) {
            loadLocalImage(url, 1);
        }
        return pic;
    } catch (Throwable e) {
        return null;
    }
}

inJustDecodeBounds = true 是整段程式的精髓:設為 true 時,decodeStream 只會把圖片的寬高填進 Options 的 outWidth / outHeight,不會真正配置像素記憶體。有了尺寸之後就能算出縮放比例,再設回 false 做第二次真正的解碼。這個技巧至今仍是 Android 上載入大圖的標準做法。

另外還有個遞迴降採樣的版本,在遇到 OutOfMemoryError 時逐步加大 inSampleSize 重試:

private static Bitmap loadLocalImage(String url, int inSampleSize) {
    if (!new File(url).exists()) return null;
    if (url.endsWith(".mp4") || url.endsWith(".3gp")) {
        return loadLocalImageByVideo(url);   // 影片走縮圖 API
    }

    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inSampleSize = inSampleSize;

    InputStream is = null;
    try {
        is = new FileInputStream(url);
        if (is != null) {
            Bitmap map = BitmapFactory.decodeStream(is, null, opt);
            if (map == null) return null;
            int height = map.getHeight();
            int width = map.getWidth();
            if (width > 1920 || height > 1080) {
                inSampleSize = (inSampleSize == 0) ? 2 : inSampleSize + 1;
                is.close();
                map.recycle();
                map = null;
                return loadLocalImage(url, inSampleSize);   // 遞迴重試
            } else {
                return map;
            }
        }
    } catch (OutOfMemoryError e) {
        System.gc();
        if (inSampleSize < 50) {
            inSampleSize = (inSampleSize == 0) ? 2 : inSampleSize + 1;
            return loadLocalImage(url, inSampleSize);
        } else {
            return null;
        }
    } finally {
        if (is != null) {
            try { is.close(); } catch (Exception e) { }
        }
        System.gc();
    }
    return null;
}

這裡遞迴搭配 inSampleSize 上限 50 是個不錯的防護,避免 OOM 之後陷入無限重試。但用 System.gc() 來救場其實效果有限,它只是「建議」虛擬機回收,並不保證執行,而且在 UI 流程中頻繁呼叫反而可能造成停頓。

總結:為什麼後來換掉了

回頭看這個實作,它把該考慮的都考慮到了:記憶體快取、線程池、磁碟快取、縮圖、遞迴降採樣。但實際跑起來仍然慢,原因大概是幾個細節的累積效應:

第一,executor 的核心線程數設為 1,maxPoolSize 設為 20,但 ThreadPoolExecutor 只有在佇列滿了才會擴充線程數——搭配無界佇列使用時,maxPoolSize 實際上永遠不會生效,等於全程只用一條線程在下載,這正是「慢」的直接原因。

第二,每張圖都呼叫 System.gc(),這會引發不必要的 full GC,反覆打斷下載節奏。

第三,沒有請求合併與取消機制。當列表快速滑動時,已經離開螢幕的項目仍然會把圖片下載並解碼完畢,白白浪費資源。

這三點恰好就是 Volley 的 ImageLoader 內建處理掉的事情——它把解碼放到快取線程、提供 in-flight 請求的合併、並支援請求取消。所以結論很清楚:這個自製版本的價值在於把「兩段式解碼」與「遞迴降採樣」這兩個技巧講透,但作為生產環境的圖片加載方案,還是交給成熟框架處理更合適。

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