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

動手打造 Android 圖片三級緩存加載框架:原理與實作全解析

編輯:關於 Android 程式設計

提到圖片加載的三級緩存,不少人第一反應就是「好難」。但其實只要靜下心來把流程拆開來看,親手寫上一兩遍,就會發現其中的邏輯相當清晰。本文就帶你從零梳理三級緩存的運作原理,並一步步完成實作。

所謂三級緩存,指的就是內存、檔案(外部存儲)、網路這三個層級依序回退的機制:先看記憶體裡有沒有,沒有就翻本機檔案,檔案也找不到才真的走網路下載。

對外統一的接入入口

整個框架對外只暴露一個便捷方法,呼叫端不必關心背後的細節:

public class NGImageloadHelper {
    public static void displayImage(ImageView view, String url) {
        NGDownloadImage.getInstance().addTask(url, view);
        NGDownloadImage.getInstance().doTask();
    }
}

核心的緩存調度類

真正干活的是 NGDownloadImage。它先判斷傳入的 url 對應的圖片是否已經存在於內存或檔案中;若不存在,就把這張圖包裝成一個自訂任務,丟進自建的執行緒池佇列。這裡的任務實作了 Callable 介面,在帶回調的 call 方法中觸發自訂的 TaskHandler;而 TaskHandler 會依據圖片型別調用對應的下載方法(以 HttpURLConnection 完成),下載完畢後再把 taskMap 裡對應的任務移除。

public class NGDownloadImage {
    private ExecutorService executorService;      // 執行緒池
    private NGImageMemoryCache imageMemoryCache;  // 內存緩存
    private NGImageFileCache imageFileCache;      // 檔案緩存
    private NGDownloadImageMode downloadImageMode;
    private Map<String, View> taskMap;
    private static NGDownloadImage instance;
    private int POOL_SIZE = 5;

    private NGDownloadImage() {
        final int cpuNums = Runtime.getRuntime().availableProcessors();
        executorService = Executors.newFixedThreadPool(cpuNums * POOL_SIZE);
        imageMemoryCache = new NGImageMemoryCache();
        imageFileCache = new NGImageFileCache();
        downloadImageMode = new NGDownloadImageMode();
        taskMap = new HashMap<>();
    }

    public static synchronized NGDownloadImage getInstance() {
        if (instance == null) {
            instance = new NGDownloadImage();
        }
        return instance;
    }

    // 取得圖片的完整流程:內存 → 檔案 → 網路
    public Bitmap getBitmap(String url) {
        Bitmap bitmap = imageMemoryCache.getBitmapFromCache(url);
        if (bitmap == null) {
            bitmap = imageFileCache.getImage(url);
            if (bitmap == null) {
                bitmap = getBitmapFromUrl(url);
                if (bitmap != null) {
                    imageMemoryCache.addBitmapToCache(url, bitmap);
                    imageFileCache.saveBmpToSd(url, bitmap);
                }
            } else {
                imageMemoryCache.addBitmapToCache(url, bitmap);
            }
        }
        return bitmap;
    }

    public static Bitmap getBitmapFromUrl(String path) {
        try {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                return BitmapFactory.decodeStream(inputStream);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

內存緩存的實作

內存層透過強引用與軟引用搭配來完成:強引用用 HashMap 保存熱門圖片,軟引用則用執行緒安全的 ConcurrentHashMap 承接被淘汰的物件。ConcurrentHashMap 之所以高效,靠的是鎖分離技術——它用多把鎖分別控制雜湊表不同區段(Segment)的讀寫,每個段其實就是一個小型 hashtable,可以並行運作。

淘汰策略則藉助 LinkedHashMap 的 removeEldestEntry 來完成,概念上與 LRU 頗為相似:

protected NGImageMemoryCache() {
    hashMap = new LinkedHashMap<String, Bitmap>(MAX_CACHE_CAPACITY, 0.75f, true) {
        @Override
        protected boolean removeEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) {
            if (size() > MAX_CACHE_CAPACITY) {
                mSoftBitmapCache.put(eldest.getKey(), new SoftReference<Bitmap>(eldest.getValue()));
                return true; // 移除最舊的鍵值
            }
            return false;
        }
    };
}

檔案緩存的實作

這一層的思路很單純:把圖片檔存到本地的指定資料夾,同時留意剩餘空間,空間吃緊時記得清掉最舊的圖片即可。


寫完這輪,最大的體會是:看起來唬人的技術名詞,拆開來一個個環節去理解、去動手實作,往往就沒那麼可怕了。

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