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

動手寫一個 Android 圖片加載框架:LruCache、DiskLruCache 與效能實測比較

編輯:關於 Android 程式設計

本文從零打造一個簡潔實用的 Android 圖片加載與快取框架,並就「記憶體占用」與「平均加載時間」兩個指標與主流方案 Universal Image Loader 做量化比較。寫完這個框架,你對 Bitmap 操作、LruCache、DiskLruCache 的理解會完全不一樣。若對 Bitmap 尺寸計算與 inSampleSize 不熟悉,建議先看「高效加載 Bitmap」相關文章。個人學力有限,敘述若有未精確之處,歡迎指正。

一、需求描述

一個實用的圖片加載框架至少要具備兩大能力:

圖片加載:支援不同來源(網絡、檔案系統、記憶體)、同步與異步、圖片壓縮等;

圖片快取:包含記憶體快取與磁碟快取。

1. 圖片加載

(1)同步與異步

同步:發出「調用」後必須等它返回才能繼續;異步:發出調用後不必等待即可繼續。

同步加載就是「不載完不幹別的事」,異步加載則是我們先去忙其他,載好再通知我。

(2)不同來源

網絡圖片可用 HttpURLConnection 下載解析;磁碟圖片可用 BitmapFactory.decodeFile;記憶體中的 Bitmap 直接取用即可。

(3)圖片壓縮

核心工作是計算 inSampleSize,細節在實作部分說明。

2. 圖片快取

從網絡載圖既耗時、耗電又耗流量,所以快取是必要功能。

(1)記憶體快取:存取速度遠快於磁碟,但空間有限、能存的圖較少。可用 SDK 提供的 LruCache,它採用 LRU(Least Recently Used,最近最少使用)演算法:空間不足時淘汰最久未被使用的項目。

(2)磁碟快取:能存的量大,但磁碟 IO 較慢。可用 DiskLruCache 實作,此類別不屬於 Android SDK,需自行引入原始碼。

二、快取類別的使用

1. LruCache

先看類別定義:

 public class LruCache<K, V> {
    private final LinkedHashMap<K, V> map;

    public LruCache(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }
        this.maxSize = maxSize;
        // accessOrder = true,讓 LinkedHashMap 依存取順序排序
        this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
    }
} 

LruCache 是泛型類別,內部以 LinkedHashMap 管理快取物件。

(1)初始化

 // 取得目前行程可用記憶體(KB)
    int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    int memoryCacheSize = maxMemory / 8;

    mMemoryCache = new LruCache<String, Bitmap>(memoryCacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            return bitmap.getByteCount() / 1024;   // 統一以 KB 為單位
        }
    }; 

這裡把 maxSize 設為可用記憶體的 1/8(實務上依圖片大小與頁面密度調整,1/6 到 1/4 都常見),並重寫 sizeOf 讓 LruCache 知道每個物件實際佔多少空間。

(2)取得快取物件

 public final V get(K key) {
    if (key == null) {
        throw new NullPointerException("key == null");
    }

    V mapValue;
    synchronized (this) {
        mapValue = map.get(key);
        if (mapValue != null) {
            hitCount++;
            return mapValue;
        }
        missCount++;
    }

    /*
     * 嘗試建立一個值。這段可能耗時,且 create() 返回時 map 可能已變化。
     * 若期間已有衝突的值被加入,我們保留 map 中的值並釋放剛建立的物件。
     */
    V createdValue = create(key);
    if (createdValue == null) {
        return null;
    }

    synchronized (this) {
        createCount++;
        mapValue = map.put(key, createdValue);
        if (mapValue != null) {
            map.put(key, mapValue);   // 有衝突,還原
        } else {
            size += safeSizeOf(key, createdValue);
        }
    }

    if (mapValue != null) {
        entryRemoved(false, key, createdValue, mapValue);
        return mapValue;
    } else {
        trimToSize(maxSize);
        return createdValue;
    }
} 

先嘗試依 key 取值,取不到才建立新的 key-value 對並放入 LinkedHashMap。注意它用 synchronized 做了同步,所以是線程安全的——LruCache 對所有可能涉及並發存取的公有方法都做了同步。

(3)加入快取物件

首先要決定用什麼當 key。直接用 URL 雖然直觀,但 URL 中的特殊字元可能造成問題,因此改用 URL 的 MD5 值:

 private String getKeyFromUrl(String url) {
        String key;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(url.getBytes());
            byte[] m = messageDigest.digest();
            return getString(m);
        } catch (NoSuchAlgorithmException e) {
            key = String.valueOf(url.hashCode());
        }
        return key;
    }

    private static String getString(byte[] b) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            sb.append(b[i]);
        }
        return sb.toString();
    } 

用 MD5 的好處是:不同 URL 幾乎不可能撞 key,同一個 URL 每次都得到相同 key。

取得 key 後用 put 加入快取:

 public final V put(K key, V value) {
    if (key == null || value == null) {
        throw new NullPointerException("key == null || value == null");
    }

    V previous;
    synchronized (this) {
        putCount++;
        size += safeSizeOf(key, value);
        previous = map.put(key, value);
        if (previous != null) {
            size -= safeSizeOf(key, previous);
        }
    }

    if (previous != null) {
        entryRemoved(false, key, previous, value);
    }
    trimToSize(maxSize);
    return previous;
} 

同樣有同步;放入新對後會回傳該 key 原本對應的值。

(4)刪除快取物件

 public final V remove(K key) {
    if (key == null) {
        throw new NullPointerException("key == null");
    }

    V previous;
    synchronized (this) {
        previous = map.remove(key);
        if (previous != null) {
            size -= safeSizeOf(key, previous);
        }
    }

    if (previous != null) {
        entryRemoved(false, key, previous, null);
    }
    return previous;
} 

內部會回呼 entryRemoved,若有需要可以重寫它做一些資源回收。

2. DiskLruCache

(1)初始化

DiskLruCache 只有私有建構子,因此必須用靜態方法 open 建立:

 private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) {
    this.directory = directory;
    this.appVersion = appVersion;
    this.journalFile = new File(directory, JOURNAL_FILE);
    this.journalFileTmp = new File(directory, JOURNAL_FILE_TMP);
    this.valueCount = valueCount;
    this.maxSize = maxSize;
} 
 public static DiskLruCache open(File directory, int appVersion,
            int valueCount, long maxSize) throws IOException {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }
        if (valueCount <= 0) {
            throw new IllegalArgumentException("valueCount <= 0");
        }

        // 盡量接續上次的狀態
        DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
        if (cache.journalFile.exists()) {
            try {
                cache.readJournal();
                cache.processJournal();
                cache.journalWriter = new BufferedWriter(
                        new FileWriter(cache.journalFile, true), IO_BUFFER_SIZE);
                return cache;
            } catch (IOException journalIsCorrupt) {
                cache.delete();   // 日誌損毀則整份重建
            }
        }

        // 建立一個全新的空快取
        directory.mkdirs();
        cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
        cache.rebuildJournal();
        return cache;
    } 

四個參數的意義:

directory:快取檔案的存放路徑
appVersion:應用版本號,通常填 1
valueCount:每個 key 對應的快取物件數,通常填 1
maxSize:快取總大小上限,超過時自動淘汰最久未使用者

 File diskCacheDir = getAppCacheDir(mContext, "images");
    if (!diskCacheDir.exists()) {
        diskCacheDir.mkdirs();
    }
    mDiskLruCache = DiskLruCache.open(diskCacheDir, 1, 1, DISK_CACHE_SIZE);

取得快取目錄的方法:

 public static File getAppCacheDir(Context context, String dirName) {
        String cacheDirString;
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            cacheDirString = context.getExternalCacheDir().getPath();
        } else {
            cacheDirString = context.getCacheDir().getPath();
        }
        return new File(cacheDirString + File.separator + dirName);
    } 

(2)加入快取物件

先用 getKeyFromUrl 取得 key,再透過 Editor 寫入:

 String key = getKeyFromUrl(url);
    DiskLruCache.Editor editor = mDiskLruCache.edit(key);

若該 key 正在被編輯,edit 會回傳 null,所以必須判空:

 if (editor != null) {
        // 參數為索引;我們建立時指定一個節點只有一個物件,所以傳 0
        OutputStream outputStream = editor.newOutputStream(0);
    }

寫入成功呼叫 commit,失敗則 abort 回退:

 if (getStreamFromUrl(url, outputStream)) {
        editor.commit();
    } else {
        editor.abort();   // 寫入未成功,回退整個操作
    }
    mDiskLruCache.flush();   // 把記憶體中的操作記錄同步到日誌檔

下載並寫入的實作(使用包裝流提升效率):

 public boolean getStreamFromUrl(String urlString, OutputStream outputStream) {
    HttpURLConnection urlConnection = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        bis = new BufferedInputStream(urlConnection.getInputStream(), BUF_SIZE);
        int byteRead;
        while ((byteRead = bis.read()) != -1) {
            bos.write(byteRead);
        }
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        HttpUtils.close(bis);
        HttpUtils.close(bos);
    }
    return false;
} 

(3)取得快取物件

 public synchronized Snapshot get(String key) throws IOException {
    checkNotClosed();
    validateKey(key);

    Entry entry = lruEntries.get(key);
    if (entry == null) {
        return null;
    }
    if (!entry.readable) {
        return null;
    }

    /*
     * 立刻開啟所有串流,確保讀到的是同一份已發佈的快照;
     * 若改成延遲開啟,各串流可能來自不同的編輯版本。
     */
    InputStream[] ins = new InputStream[valueCount];
    ...
    return new Snapshot(key, entry.sequenceNumber, ins);
} 

回傳的 Snapshot 是 DiskLruCache 的內部類別,提供 getInputStream 取得輸入流,再進一步解出 Bitmap。取出時一樣要做 inSampleSize 縮放以避免 OOM——計算方式與 decodeResource 相同,只是改用 decodeFileDescriptor:

 Bitmap bitmap = null;
    String key = getKeyFromUrl(url);
    DiskLruCache.Snapshot snapShot = mDiskLruCache.get(key);
    if (snapShot != null) {
        FileInputStream fileInputStream = (FileInputStream) snapShot.getInputStream(0);
        FileDescriptor fileDescriptor = fileInputStream.getFD();
        bitmap = decodeSampledBitmapFromFD(fileDescriptor, dstWidth, dstHeight);
        if (bitmap != null) {
            addBitmapToMemoryCache(key, bitmap);   // 順手寫回記憶體快取
        }
    }
 public Bitmap decodeSampledBitmapFromFD(FileDescriptor fd,
            int dstWidth, int dstHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFileDescriptor(fd, null, options);
        // calInSampleSize 的實作請見「高效加載 Bitmap」
        options.inSampleSize = calInSampleSize(options, dstWidth, dstHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFileDescriptor(fd, null, options);
    }

inJustDecodeBounds = true 的第一次解碼只讀取尺寸資訊而不真正配置像素記憶體,算好 inSampleSize 後再正式解一次,這是控制 OOM 的標準手法。

三、框架的具體實作

1. 圖片加載

(1)同步加載

必須在工作者線程執行(涉及網絡且可能耗時)。順序是:先查記憶體快取 → 再查磁碟快取 → 都沒有才從網絡抓取並寫入磁碟快取。

 public Bitmap loadBitmap(String url, int dstWidth, int dstHeight) {
    Bitmap bitmap = loadFromMemory(url);
    if (bitmap != null) {
        return bitmap;
    }

    // 記憶體快取沒有
    try {
        bitmap = loadFromDisk(url, dstWidth, dstHeight);
        if (bitmap != null) {
            return bitmap;
        }

        // 磁碟快取也沒有
        bitmap = loadFromNet(url, dstWidth, dstHeight);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return bitmap;
} 

(2)異步加載

實務上更常用:呼叫後立刻返回,框架在背景載好之後直接把圖片設到指定的 ImageView 上。

 public void displayImage(String url, ImageView imageView,
            int dstWidth, int widthHeight) {
    imageView.setTag(IMG_URL, url);

    Bitmap bitmap = loadFromMemory(url);
    if (bitmap != null) {
        imageView.setImageBitmap(bitmap);
        return;
    }

    Runnable loadBitmapTask = new Runnable() {
        @Override
        public void run() {
            Bitmap bitmap = loadBitmap(url, dstWidth, dstHeigth);
            if (bitmap != null) {
                // Result 是自訂類別,封裝 Bitmap、URL 與作為容器的 ImageView
                Result result = new Result(bitmap, url, imageView);
                Message msg = mMainHandler.obtainMessage(MESSAGE_SEND_RESULT, result);
                msg.sendToTarget();
            }
        }
    };
    threadPoolExecutor.execute(loadBitmapTask);
} 

異步與同步的差別就在於「把耗時任務丟進線程池」。obtainMessage 會從內部訊息池取出一個 Message 複用(概念與線程池複用線程相同),比 new 一個更有效率;第一個參數是 what(訊息標識),第二個是 obj(附帶的資料物件,就像郵件的附件)。

 private static final int CORE_POOL_SIZE = CPU_COUNT + 1;      // CPU 數 + 1
    private static final int MAX_POOL_SIZE = 2 * CPU_COUNT + 1;   // CPU 數 × 2 + 1
    private static final long KEEP_ALIVE = 5L;                    // 存活 5 秒

    public static final Executor threadPoolExecutor = new ThreadPoolExecutor(
            CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS,
            new LinkedBlockingQueue<Runnable>());

    private Handler mMainHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            Result result = (Result) msg.obj;
            ImageView imageView = result.imageView;
            String url = (String) imageView.getTag(IMG_URL);
            if (url.equals(result.url)) {
                imageView.setImageBitmap(result.bitmap);
            } else {
                Log.w(TAG, "The url associated with imageView has changed");
            }
        }
    }; 

這裡有個非常關鍵的細節:設定圖片前先比對 ImageView 上的 URL 是否與結果的 URL 相同。原因是 ListView 與 RecyclerView 會複用 item 的 View——剛滑出螢幕的 item 圖片還在載入,這個 View 被新 item 拿去用時圖片才載完,就會出現「A 的圖出現在 B 的位置」這種經典 bug。加上 URL 比對就能避免。

2. 圖片快取

(1)快取的建立

 private LruCache<String, Bitmap> mMemoryCache;
    private DiskLruCache mDiskLruCache;

    private ImageLoader(Context context) {
        mContext = context.getApplicationContext();   // 用 Application Context 避免洩漏

        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
        int cacheSize = maxMemory / 8;
        mMemorySize = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeof(String key, Bitmap bitmap) {
                return bitmap.getByteCount() / 1024;
            }
        };

        File diskCacheDir = getAppCacheDir(mContext, "images");
        if (!diskCacheDir.exists()) {
            diskCacheDir.mkdirs();
        }
        if (diskCacheDir.getUsableSpace() > DISK_CACHE_SIZE) {
            // 剩餘空間大於我們設定的磁碟快取大小才建立
            try {
                mDiskLruCache = DiskLruCache.open(diskCacheDir, 1, 1, DISK_CACHE_SIZE);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } 

(2)快取的取得與加入

 private void addToMemoryCache(String key, Bitmap bitmap) {
    if (getFromMemoryCache(key) == null) {   // 不存在時才加入
        mMemoryCache.put(key, bitmap);
    }
}

private Bitmap getFromMemoryCache(String key) {
    return mMemoryCache.get(key);
}
 private Bitmap loadFromDiskCache(String url, int dstWidth, int dstHeight)
            throws IOException {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        // 不該在主線程做磁碟 IO,只記警告
        Log.w(TAG, "should not load Bitmap in main thread");
    }
    if (mDiskLruCache == null) {
        return null;
    }

    Bitmap bitmap = null;
    String key = getKeyFromUrl(url);
    DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
    if (snapshot != null) {
        FileInputStream fileInputStream = (FileInputStream) snapshot.getInputStream(0);
        FileDescriptor fileDescriptor = fileInputStream.getFD();
        bitmap = decodeSampledBitmapFromFD(fileDescriptor, dstWidth, dstHeight);
        if (bitmap != null) {
            addToMemoryCache(key, bitmap);
        }
    }
    return bitmap;
}

把圖片寫進磁碟快取的工作在 loadFromNet 完成:

 private Bitmap loadFromNet(String url, int dstWidth, int dstHeight)
            throws IOException {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        // 主線程訪問網絡會直接崩潰,提早拋出以免白做一堆前置工作
        throw new RuntimeException("Do not load Bitmap in main thread.");
    }
    if (mDiskLruCache == null) {
        return null;
    }

    String key = getKeyFromUrl(url);
    DiskLruCache.Editor editor = mDiskLruCache.edit(key);
    if (editor != null) {
        OutputStream outputStream = editor.newOutputStream(0);
        if (getStreamFromUrl(url, outputStream)) {
            editor.commit();
        } else {
            editor.abort();
        }
        mDiskLruCache.flush();
    }
    return loadFromDiskCache(url, dstWidth, dstHeight);
} 

兩個方法開頭都檢查了是否在主線程,但策略不同:磁碟 IO 在主線程只是效能問題,因此只記警告;網絡在主線程則是硬性禁止,所以直接拋例外——提早失敗比做完一堆前置功課才發現不能執行要好。

同理,開頭都判斷了 mDiskLruCache 是否為 null。若做完所有準備才發現快取根本沒初始化成功,那就太冤了。

四、簡單的效能測試

關於效能最佳實踐,Android Developer 官方文件與社區整理都有完整方案。這裡只從記憶體分配與平均加載時間兩個角度看這個框架是否「勉強可用」。

1. 記憶體分配

跑起 demo,等圖片載完,用 adb 查看:

Dalvik Heap 分配 18003KB,Native Heap 分配 6212KB。

2. 平均加載時間

 // 加載前的時間點
    long beforeTime = System.currentTimeMillis();
    // 加載完成的時間點
    long afterTime = System.currentTimeMillis();
    // total 為圖片總數,averTime 為每張平均所需時間
    int averTime = (int) ((afterTime - beforeTime) / total);

再維護一個計數器 counts,每載完一張加一,當 counts 等於 total 時回呼 onAfterLoad 計算平均值。實測載入 30 張圖片,平均每張約 1.265 秒。

3. 與 UIL 的比較

用 UIL 載同樣的 30 張圖,記憶體情況如下:

Native Heap 部分兩者差不多;Dalvik Heap 部分 UIL 幾乎是我們的兩倍。由於兩個框架的量級完全不同,這不能說明我們在記憶體上優於 UIL,但至少表示這個自製框架勉強可用。

平均加載時間方面,UIL 實測約 1.516 秒。同樣考慮量級差異,我們的框架在載入速度上仍有明顯提升空間。

五、還可以更好

寫完會發現,實作一個具備基本功能的圖片加載框架並不複雜,但能做的還很多:

  • 自動計算目標尺寸。目前異步加載需顯式傳入期望寬高,實用框架應該能依 ImageView 的實際尺寸自動推算。
  • 模組化。目前整個框架塞在一個類別中,應該拆成下載器、解碼器、快取層、載入任務派發器等獨立單元。
  • 列表可見性暫停。快速滑動時應取消離開畫面的請求,避免浪費帶寬與 CPU。
  • 載入動畫與佔位圖。提供 placeholder、error 圖與淡入效果,是成熟框架的基本配備。
  • 請求優先級與去重。同一 URL 同時被多處請求時只應實際下載一次。
  • 成熟方案優先。Glide、Coil 已在快取策略、生命週期感知、轉場動畫等細節上打磨多年,量產專案直接採用會省下可觀成本。

以上就是本文的全部內容,希望對大家的學習有所幫助。

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