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

Android 磁碟緩存 DiskLruCache 完全指南與自製圖片加載器

編輯:關於 Android 程式設計

DiskLruCache 是一套硬碟(磁碟)緩存方案,淘汰策略與 LruCache 同源,都基於 LRU 演算法——最近最少使用的數據優先被清掉。

需要特別說明的是,這個類並不在 Android SDK 裡,它由開源社群維護,需要自行下載原始碼放進專案(常見做法是從 AOSP 的 libcore 中取得)。

一、DiskLruCache 基本用法

1. 初始化

唯一的入口是靜態方法 open():

public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
  • directory:緩存存放目錄,通常選用應用內部或外部緩存資料夾,這樣卸載時數據會一起被清除。
  • appVersion:當前應用版本號。版本一旦變化,該目錄下的所有緩存都會失效清空。
  • valueCount:同一個 key 可以對應幾個檔案,一般傳 1,讓 key 與檔案一一對應。
  • maxSize:允許佔用的最大位元組數,超標時演算法會自動淘汰舊數據。

a. 挑一個合適的緩存目錄

public File getDiskCacheDir(Context context, String uniqueName) {
    String cachePath;
    if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
            || !Environment.isExternalStorageRemovable()) {
        cachePath = context.getExternalCacheDir().getPath();
    } else {
        cachePath = context.getCacheDir().getPath();
    }
    File cacheDir = new File(cachePath + File.separator + uniqueName);
    if (!cacheDir.exists()) {
        cacheDir.mkdirs();
    }
    return cacheDir;
}

邏輯是:SD 卡存在或不可移除時用 getExternalCacheDir(),路徑形如 /sdcard/Android/data/<包名>/cache;否則退回 getCacheDir(),路徑形如 /data/data/<包名>/cache。前者空間更大,通常是我們的首選。

b. 取得版本號

public int getAppVersion(Context context) {
    try {
        PackageInfo info = context.getPackageManager()
                .getPackageInfo(context.getPackageName(), 0);
        return info.versionCode;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    return 1;
}

c. 組合起來

private DiskLruCache mDiskCache;
private long DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB

File cacheDir = getDiskCacheDir(mContext, "Bitmap");
mDiskCache = DiskLruCache.open(cacheDir, getAppVersion(context), 1, DISK_CACHE_SIZE);

2. 寫入緩存

寫入要靠 DiskLruCache.Editor,透過 edit(key) 取得:

public Editor edit(String key) throws IOException

這個 key 會成為檔名,並與資源 URL 一一對應。直接把 URL 當 key 並不合適——URL 裡常有 /、?、& 等在檔名中不合法的字符。最省事的做法是對 URL 做一次 MD5,結果既唯一,又只包含 0-F,完全符合命名規則。

public String hashKeyForDisk(String key) {
    String cacheKey;
    try {
        final MessageDigest mDigest = MessageDigest.getInstance("MD5");
        mDigest.update(key.getBytes());
        cacheKey = bytesToHexString(mDigest.digest());
    } catch (NoSuchAlgorithmException e) {
        cacheKey = String.valueOf(key.hashCode());
    }
    return cacheKey;
}

private String bytesToHexString(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < bytes.length; i++) {
        String hex = Integer.toHexString(0xFF & bytes[i]);
        if (hex.length() == 1) {
            sb.append('0');
        }
        sb.append(hex);
    }
    return sb.toString();
}

取得 Editor 並寫資料:

String imageUrl = "https://.....jpg";
String key = hashKeyForDisk(imageUrl);
DiskLruCache.Editor editor = mDiskLruCache.edit(key);
if (editor != null) {
    OutputStream outputStream = editor.newOutputStream(0);
    if (downloadUrlToStream(url, outputStream)) {
        editor.commit();   // 提交,寫入才會生效
    } else {
        editor.abort();    // 放棄本次寫入
    }
    mDiskCache.flush();    // 把操作記錄落盤
}

下載並寫流的實現:

private boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;
    BufferedInputStream in = null;
    try {
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        in = new BufferedInputStream(urlConnection.getInputStream(), 8 * 1024);
        out = new BufferedOutputStream(outputStream, 8 * 1024);
        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        return true;
    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        try {
            if (out != null) out.close();
            if (in != null) in.close();
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}

newOutputStream() 的 index 參數取決於 valueCount,這裡是 1,所以傳 0。

3. 讀取緩存

a. 先用 get() 拿到 Snapshot 物件:

public synchronized Snapshot get(String key) throws IOException
String key = hashKeyForDisk(imageUrl);
DiskLruCache.Snapshot snapShot = mDiskLruCache.get(key);

b. 從 Snapshot 取得輸入流(index 同樣傳 0):

InputStream is = snapShot.getInputStream(0);

c. 解成 Bitmap:

Bitmap bitmap = BitmapFactory.decodeStream(is);

4. 刪除與統計

// 刪除單個 key,日常很少手動調用,因為淘汰由 maxSize 自動完成
public synchronized boolean remove(String key) throws IOException

// 目前緩存總大小(位元組),可用於設置頁顯示佔用空間
public synchronized long size()

// 清空全部緩存,實現「手動清理」功能
public void delete() throws IOException

5. 刷新狀態(重要)

public synchronized void flush() throws IOException {
    checkNotClosed();
    trimToSize();
    journalWriter.flush();
}

這個方法把記憶體中的操作記錄同步到 journal 日誌檔。它非常重要——DiskLruCache 能正常工作的前提就是依賴 journal 的內容。實踐中可以在 Activity 的 onPause() 裡調一次。

二、封裝成圖片加載器

把上述能力封裝進一個單例的 DiskCacheImageLoader,對外只暴露「加載」與「取消」兩個動作,內部用 AsyncTask 承擔網路請求。

public class DiskCacheImageLoader {

    private Context mContext;
    private Set<DiskCacheAsyncTask> mTaskSet;
    private DiskLruCache mDiskCache;
    private static DiskCacheImageLoader mDiskCacheImageLoader;

    public static DiskCacheImageLoader getInstance(Context context) {
        if (mDiskCacheImageLoader == null) {
            synchronized (DiskCacheImageLoader.class) {
                if (mDiskCacheImageLoader == null) {
                    mDiskCacheImageLoader = new DiskCacheImageLoader(context);
                }
            }
        }
        return mDiskCacheImageLoader;
    }

    private DiskCacheImageLoader(Context context) {
        mTaskSet = new HashSet<>();
        mContext = context.getApplicationContext();
        File diskCacheDir = getDiskCacheDir(mContext, "Bitmap");
        if (!diskCacheDir.exists()) {
            diskCacheDir.mkdirs();
        }
        try {
            mDiskCache = DiskLruCache.open(diskCacheDir, 1, 1, 1024 * 1024 * 20);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /** 對外主入口:先查緩存,命中就直接顯示,否則異步下載 */
    public void loadImage(ImageView imageView, String url) {
        Bitmap bitmap = null;
        try {
            bitmap = getBitmapFromDiskCache(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bitmap == null) {
            DiskCacheAsyncTask task = new DiskCacheAsyncTask(imageView);
            task.execute(url);
            mTaskSet.add(task);
        } else {
            imageView.setImageBitmap(bitmap);
        }
    }

    /** 只加載 ListView 當前可見區間內的圖片,避免無效請求 */
    public void loadTagedImagesInListView(int start, int end, String[] urls, ListView mListView) {
        for (int i = start; i < end; i++) {
            String url = urls[i];
            ImageView imageView = (ImageView) mListView.findViewWithTag(url);
            loadImage(imageView, url);
        }
        Log.i("num of task", " " + mTaskSet.size());
    }

    private Bitmap getBitmapFromDiskCache(String url) throws IOException {
        if (mDiskCache == null) return null;
        String key = hashKeyFormUrl(url);
        DiskLruCache.Snapshot snapShot = mDiskCache.get(key);
        if (snapShot != null) {
            InputStream ins = snapShot.getInputStream(0);
            return BitmapFactory.decodeStream(ins);
        }
        return null;
    }

    private Bitmap addBitmapToDiskCache(String url) throws IOException {
        if (mDiskCache == null) return null;
        String key = hashKeyFormUrl(url);
        DiskLruCache.Editor editor = mDiskCache.edit(key);
        if (editor != null) {
            OutputStream outputStream = editor.newOutputStream(0);
            if (downloadUrlToStream(url, outputStream)) {
                editor.commit();
            } else {
                editor.abort();
            }
            mDiskCache.flush();
        }
        return getBitmapFromDiskCache(url);
    }

    /** 列表滑動時取消所有在飛的請求 */
    public void cancelAllTask() {
        if (mTaskSet != null) {
            for (DiskCacheAsyncTask task : mTaskSet) {
                task.cancel(false);
            }
            mTaskSet.clear();
            Log.i("num of task", " " + mTaskSet.size());
        }
    }

    private class DiskCacheAsyncTask extends AsyncTask<String, Void, Bitmap> {
        private ImageView imageView;

        public DiskCacheAsyncTask(ImageView imageView) {
            this.imageView = imageView;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = getBitmapFromURL(params[0]);
            if (bitmap != null) {
                try {
                    addBitmapToDiskCache(params[0]);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            if (imageView != null && bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
            mTaskSet.remove(this);
            Log.i("num of task", " " + mTaskSet.size());
        }
    }
}

三、接入 ListView

效果目標:首次進入時從網路加載;斷網退出後再進來,直接從本地 DiskLruCache 讀取。

核心思路是「滑動中取消、停下來才加載」,這樣能大幅降低共識請求量:

listView.setOnScrollListener(new AbsListView.OnScrollListener() {
    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
        if (scrollState == SCROLL_STATE_IDLE) {
            mDiskImageLoader.loadTagedImagesInListView(mStart, mEnd, urls, listView);
        } else {
            mDiskImageLoader.cancelAllTask();
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        mStart = firstVisibleItem;
        mEnd = firstVisibleItem + visibleItemCount;
        if (mFirstIn && visibleItemCount > 0) {
            mDiskImageLoader.loadTagedImagesInListView(mStart, mEnd, urls, listView);
            mFirstIn = false;
        }
    }
});

需要補充的是,只用磁碟緩存並不足以撐起流暢的列表——每次命中緩存仍然要解碼一次,開銷不小。成熟方案(如 Glide、Fresco)都是「記憶體緩存 + 磁碟緩存」雙層結構,並加上請求去重與圖片複用。本文的 DiskLruCache 正是那層磁碟緩存的地基。

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