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

Universal-Image-Loader 學習系列:磁碟緩存策略源碼剖析

編輯:關於 Android 程式設計

本文聚焦 Universal-Image-Loader(UIL)的磁碟(硬盤)緩存策略。

其中,LimitedAgeDiscCache 用於設定檔案存活的最長時間,一旦超過該門檻便會刪除對應檔案;而 UnlimitedDiscCache 則對緩存沒有任何限制。

繼承關係如下:

 public class LimitedAgeDiscCache extends BaseDiscCache public abstract class BaseDiscCache implements DiskCache public interface DiskCache extends DiscCacheAware public interface DiscCacheAware

下面由底向上逐層解析。

1、DiscCacheAware 介面

 public interface DiscCacheAware { /** 返回硬盤緩存的 root directory */ File getDirectory(); /** 返回緩存圖片的 file,未緩存時返回 null */ File get(String imageUri); /** 保存 image bitmap 到硬盤緩存中 */ boolean save(String imageUri, InputStream imageStream, IoUtils.CopyListener listener) throws IOException; /** (重載)保存 image bitmap 到硬盤緩存中 */ boolean save(String imageUri, Bitmap bitmap) throws IOException; /** 根據給定 URI 刪除對應的 image file */ boolean remove(String imageUri); /** 關閉硬盤緩存,釋放資源 */ void close(); /** 清除硬盤緩存 */ void clear(); }

上述程式碼中用到 IoUtils.CopyListener:

 public static interface CopyListener { /** * @param current 已經加載的 bytes * @param total 需要加載的總共 bytes * @return true 表示繼續拷貝,false 表示中斷 */ boolean onBytesCopied(int current, int total); } 

以及 ImageLoadingProgressListener:

 public interface ImageLoadingProgressListener { /** 當加載進程改變時被調用 */ void onProgressUpdate(String imageUri, View view, int current, int total); }

2、DiskCache 介面

 public interface DiskCache extends DiscCacheAware { }

3、BaseDiscCache 抽象類

BaseDiscCache 實現了絕大多數緩存邏輯:預設緩衝區大小為 32 Kb,預設壓縮格式為 PNG、品質 100。核心方法包括 getFile()(依 URI 取得檔案物件)、save()(先寫入 .tmp 暫存檔,成功後再 renameTo 正式檔案,失敗則刪除暫存檔)與 clear()(清空緩存目錄)等。其中 save() 透過 IoUtils.copyStream 把輸入流寫入輸出流,並在過程中回報進度、支援中途中斷。

這裡涉及幾個值得留意的工具方法:

IoUtils.copyStream:以 bufferSize 為單位循環讀寫,每完成一步便回呼 listener.onBytesCopied;當載入進度已超過 75% 時,即使 listener 要求中斷也會繼續完成,避免半途而廢。

 public static boolean copyStream(InputStream is, OutputStream os, CopyListener listener, int bufferSize) throws IOException { int current = 0; int total = is.available(); if (total <= 0) { total = DEFAULT_IMAGE_TOTAL_SIZE; } final byte[] bytes = new byte[bufferSize]; int count; if (shouldStopLoading(listener, current, total)) return false; while ((count = is.read(bytes, 0, bufferSize)) != -1) { os.write(bytes, 0, count); current += count; if (shouldStopLoading(listener, current, total)) return false; } os.flush(); return true; }

IoUtils.closeSilently:靜默關閉 Closeable 資源,吞掉異常以免影響主流程。

 public static void closeSilently(Closeable closeable) { try { closeable.close(); } catch (Exception e) { // Do nothing } }

File.renameTo:將檔案重新命名,需要來源與目標目錄的寫入權限,失敗時返回 false。

4、LimitedAgeDiscCache 源碼

這是一種時間策略:刪除「加載時間超過限定時長」的檔案,緩存容量本身則無限制。它內部以一個 Map 記錄每個檔案的載入時間,在 get() 時判斷檔案是否過期,過期則刪除;在 save() 時透過 rememberUsage() 更新檔案的最後修改時間。

 public class LimitedAgeDiscCache extends BaseDiscCache { private final long maxFileAge; private final Map loadingDates = Collections.synchronizedMap(new HashMap()); public LimitedAgeDiscCache(File cacheDir, long maxAge) { this(cacheDir, null, DefaultConfigurationFactory.createFileNameGenerator(), maxAge); } public LimitedAgeDiscCache(File cacheDir, File reserveCacheDir, FileNameGenerator fileNameGenerator, long maxAge) { super(cacheDir, reserveCacheDir, fileNameGenerator); this.maxFileAge = maxAge * 1000; // 轉化為 milliseconds } @Override public File get(String imageUri) { File file = super.get(imageUri); if (file != null && file.exists()) { boolean cached; Long loadingDate = loadingDates.get(file); if (loadingDate == null) { cached = false; loadingDate = file.lastModified(); } else { cached = true; } // 刪除策略 if (System.currentTimeMillis() - loadingDate > maxFileAge) { file.delete(); loadingDates.remove(file); } else if (!cached) { loadingDates.put(file, loadingDate); } } return file; } private void rememberUsage(String imageUri) { File file = getFile(imageUri); long currentTime = System.currentTimeMillis(); file.setLastModified(currentTime); loadingDates.put(file, currentTime); } }

5、UnlimitedDiscCache 源碼

這是 UIL 框架中預設的 DiskCache 實現,緩存容量不受限制,僅是 BaseDiscCache 的簡單封裝:

 public class UnlimitedDiscCache extends BaseDiscCache { public UnlimitedDiscCache(File cacheDir) { super(cacheDir); } public UnlimitedDiscCache(File cacheDir, File reserveCacheDir) { super(cacheDir, reserveCacheDir); } public UnlimitedDiscCache(File cacheDir, File reserveCacheDir, FileNameGenerator fileNameGenerator) { super(cacheDir, reserveCacheDir, fileNameGenerator); } }

總的來說,UIL 的磁碟緩存設計以 DiscCacheAware 為頂層契約,BaseDiscCache 承載通用讀寫邏輯,再由其派生出 UnlimitedDiscCache(無限制)與 LimitedAgeDiscCache(限時失效)兩種具體策略,兼顧了靈活性與擴展性。

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