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

動手打造高效能 Android ImageLoader:三級快取與按需解碼實作

編輯:關於 Android 程式設計

幾乎每個 Android 專案都要處理圖片的下載與顯示,於是 ImageLoader 幾乎成了標配。市面上確實有不少優秀的開源框架可用,效能好、API 也親切;但如果能自己從零實作一個,技術樹上無疑又多了一根亮眼的枝幹。以下就來拆解一個高效 ImageLoader 該具備什麼,以及怎麼把它寫出來。

歸納來說,優秀的 ImageLoader 大致有這些共同特徵:支援同步與非同步載入、能依需要縮放、具備記憶體快取、具備磁碟快取、能從網路拉取、呼叫方式簡潔,而且效能要過關。接下來的實作,我們就朝這個目標靠攏。

為什麼不再用軟引用與弱引用

幾年前,很多開發者會用 SoftReference 或 WeakReference 來做圖片多級快取,但如今這招已經不可靠,主要有兩個風險:

其一,從 Android 2.3(API Level 9)開始,垃圾回收器變得更積極地回收持有軟/弱引用的物件,快取隨時可能被清空。

其二,Android 3.0(API Level 11)之後,圖片位元資料存放在本地堆記憶體中,無法以可預期的方式主動釋放,容易累積出記憶體溢出並導致崩潰。

因此我們改用 Android 3.1 起提供的 LruCache 來做記憶體快取(若你要支援更早的版本,需引入 android-support-v4)。LruCache 採「最近最少使用」策略:當快取內圖片的總大小超過設定上限時,自動淘汰最久沒被存取的項目。記憶體快取就這樣定案。

磁碟快取這層,最直觀的做法是用基本的檔案讀寫做資料備份,方便日後取用,其實不需要多複雜的演算法。不過業界目前普遍採用 DiskLruCache,反響良好的幾個圖片框架也都用它,於是這裡同樣採用它,好處是淘汰策略成熟、對磁碟寫入也友善。

技術選型底定,開始寫程式。

對外 API:同步與非同步

我們提供兩種呼叫方式:

/**
 * 非同步載入圖片並綁定到 ImageView
 */
public void bind(String resource, ImageView imageView, int reqWidth, int reqHeight) {
}

/**
 * 同步載入圖片
 */
public Bitmap load(String resource, int reqWidth, int reqHeight) {
    Bitmap bitmap = null;
    return bitmap;
}

取值順序遵循效率由高到低:記憶體快取 > SD 卡快取 > 網路請求。

初始化配置

我們用一個 ImgLoaderConfig 物件集中管理設定,先放三個核心屬性,日後需要再擴充:

/** 記憶體快取大小 */
private int memoryCacheSize;
/** SD 卡快取大小 */
private long diskCacheSize;
/** SD 卡快取路徑 */
private String diskCachePath;

有了設定物件,就能寫初始化邏輯:

/**
 * 初始化方法
 *
 * @param config  圖片載入框架設定
 * @param context 上下文
 */
public void init(ImgLoaderConfig config, Context context) {
    if (null == context) {
        throw new IllegalArgumentException("the context could not is null");
    }
    if (config.getMemoryCacheSize() <= 0) {
        int maxMemory = (int) Runtime.getRuntime().maxMemory() / 1024;
        memoryCacheSize = maxMemory / 8;
    } else {
        memoryCacheSize = config.getMemoryCacheSize();
    }
    if (config.getDiskCacheSize() <= 0) {
        diskCacheSize = DISK_CACHE_SIZE;
    } else {
        diskCacheSize = config.getDiskCacheSize();
    }
    mMemoryCache = new LruCache(memoryCacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap value) {
            // 計算 bitmap 佔用的記憶體,高版本 API 可用 value.getByteCount()
            return value.getRowBytes() * value.getHeight() / 1024;
        }
    };
    if (TextUtils.isEmpty(config.getDiskCachePath())) {
        diskCachePath = context.getCacheDir().getAbsolutePath();
    } else {
        diskCachePath = config.getDiskCachePath();
    }
    File file = new File(diskCachePath);
    if (!file.exists()) {
        file.mkdirs();
    }
    try {
        mDiskLruCache = DiskLruCache.open(file, 1, 1, diskCacheSize);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

第一級:記憶體快取

/**
 * 將 bitmap 加入記憶體快取
 */
private void addImg2Memory(String key, Bitmap bitmap) {
    if (null == mMemoryCache) {
        throw new IllegalArgumentException("the memoryCache could not be null");
    }
    if (null == mMemoryCache.get(key)) {
        mMemoryCache.put(key, bitmap);
    }
}

/**
 * 依 key 從記憶體快取取出 bitmap
 */
private Bitmap loadImgFromMemory(String key) {
    if (null == mMemoryCache) {
        throw new IllegalArgumentException("the memoryCache could not be null");
    }
    if (mMemoryCache.size() < 1) {
        return null;
    }
    return mMemoryCache.get(key);
}

第二級:磁碟快取

記憶體找不到,就往下找磁碟。這裡有個容易忽略的細節:不能直接拿網路網址當 key,因為網址可能帶有非法字元或特殊符號,實務上會先轉成 MD5 字串再當作快取鍵。

/**
 * 將圖片寫入 SD 卡快取
 */
private void addImg2Disk(String key, InputStream inputStream) {
    String MD5key = MD5Util.getMD5Str(key);
    try {
        DiskLruCache.Editor editor = mDiskLruCache.edit(MD5key);
        OutputStream outputStream = editor.newOutputStream(0);
        if (writeImgToDisk(outputStream, inputStream)) {
            editor.commit();
        } else {
            editor.abort();
        }
        mDiskLruCache.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * 串流寫入磁碟
 */
private boolean writeImgToDisk(OutputStream outputStream, InputStream inputStream) {
    BufferedInputStream bis = new BufferedInputStream(inputStream);
    BufferedOutputStream bos = new BufferedOutputStream(outputStream);
    int b;
    try {
        while ((b = bis.read()) != -1) {
            bos.write(b);
        }
        bis.close();
        bos.flush();
        bos.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}

/**
 * 從磁碟快取載入圖片,並順便回填記憶體快取
 */
private Bitmap loadImgFromDisk(String key, int reqWidth, int reqHeight) {
    Bitmap bitmap = null;
    String MD5key = MD5Util.getMD5Str(key);
    try {
        DiskLruCache.Snapshot snapshot = mDiskLruCache.get(MD5key);
        if (null != snapshot) {
            FileInputStream fileInputStream = (FileInputStream) snapshot.getInputStream(0);
            FileDescriptor fd = fileInputStream.getFD();
            bitmap = ImgResizer.decodeFromFileDescriptor(fd, reqWidth, reqHeight);
            if (null != bitmap) {
                addImg2Memory(key, bitmap);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bitmap;
}

第三級:網路拉取

兩層快取都落空,才真的走網路。這裡只給最直白的請求方式;至於執行緒池調度、斷點續傳等優化,值得另開一篇細談。

/**
 * 從網路取得圖片串流
 */
private InputStream reqImgFromHttp(String url) {
    try {
        URL httpUrl = new URL(url);
        return httpUrl.openConnection().getInputStream();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

把三級快取串起來

快取層寫完,回到一開始宣告的 bind 方法。這裡說明非同步版本:

/**
 * 以非同步方式把圖片綁定到控制項
 */
public void bind(final String source, final ImageView img, final int reqWidth, final int reqHeight) {
    if (TextUtils.isEmpty(source) || img == null) {
        return;
    }
    Bitmap bitmap = loadImgFromMemory(source);
    if (null != bitmap) {
        img.setImageBitmap(bitmap);
    } else {
        bitmap = loadImgFromDisk(source, reqWidth, reqHeight);
        if (null != bitmap) {
            img.setImageBitmap(bitmap);
        } else {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    InputStream inputStream = reqImgFromHttp(source);
                    addImg2Disk(source, inputStream);
                    final Bitmap bitmap = ImgResizer.decodeFromStream(inputStream, reqWidth, reqHeight);
                    if (bitmap == null) {
                        return;
                    }
                    addImg2Memory(source, bitmap);
                    // 切回主執行緒更新 UI
                    Handler handler = new Handler(Looper.getMainLooper());
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            img.setImageBitmap(bitmap);
                        }
                    });
                }
            }).start();
        }
    }
}

按需縮放:ImgResizer

最後一塊拼圖是按需解碼,避免把一張大圖原尺寸塞進記憶體。核心技巧是先用 inJustDecodeBounds = true 只讀取尺寸資訊,算出合適的 inSampleSize 後再真正解碼:

package com.york.devbase.imgload;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.FileDescriptor;
import java.io.InputStream;

public class ImgResizer {

    /**
     * 計算縮放倍率
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        if (reqWidth == 0 || reqHeight == 0) {
            return 1;
        }
        final int width = options.outWidth;
        final int height = options.outHeight;
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            int halfWidth = width / 2;
            int halfHeight = height / 2;
            // 確保倍率同時滿足寬與高的限制
            while ((halfWidth / inSampleSize) > reqWidth) {
                inSampleSize++;
            }
            while ((halfHeight / inSampleSize) > reqHeight) {
                inSampleSize++;
            }
        }
        return inSampleSize;
    }

    /**
     * 從檔案描述符讀取並縮放 bitmap
     * 這裡不用 decodeFile(),因為 FileInputStream 是有序串流,
     * 連續兩次解碼會受前一次讀取位置影響,導致第二次拿到 null
     */
    public static Bitmap decodeFromFileDescriptor(FileDescriptor fd, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fd, null, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFileDescriptor(fd, null, options);
    }

    /**
     * 從串流解析並按需縮放
     */
    public static Bitmap decodeFromStream(InputStream inputStream, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(inputStream, null, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeStream(inputStream, null, options);
    }
}

使用方式

呼叫端非常直觀:

ImgLaodManager imgLaodManager = new ImgLaodManager();
imgLaodManager.init(new ImgLoaderConfig(), this);
imgLaodManager.bind("https://upload.news.cecb2b.com/2014/1209/1418100017289.jpg",
        mImageView, ScreenUtils.dip2px(100), ScreenUtils.dip2px(100));

至此,三級快取與非同步載入的雛形就完成了。後續若要投入正式專案,還有幾個方向值得補強:快取命中時的圖片切換動畫、請求取消與生命週期綁定、以及磁碟快取的容量預估。把這些補齊,它就能勝任多數列表頁的圖片載入需求。

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