編輯:關於 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
下面由底向上逐層解析。
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); } public interface DiskCache extends DiscCacheAware { }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。
這是一種時間策略:刪除「加載時間超過限定時長」的檔案,緩存容量本身則無限制。它內部以一個 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); } } 這是 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(限時失效)兩種具體策略,兼顧了靈活性與擴展性。
八個好用的 Android Studio 插件推薦
Android Studio 功能全面,為從智慧手錶到汽車等各類設備的 Android 開發提供了完整支援。而它對第三方插件的良好支持,更讓開發如虎添翼。本文精選了八個實
Android 專案加入 ProGuard 混淆:規則設定與第三方庫排除
為 Android 程式加入代碼混淆器,核心工作就是在 proguard-project.txt 中撰寫規則(早期 ADT 專案使用的是 proguard.cfg)。以下
Android中SQLite數據庫的使用詳解
一、簡介 SQLite是一款輕量級的數據庫管理系統(DBMS)。它以單個文件的形式存儲數據,Android標準庫自帶SQLite庫及配套的Java輔助類。其主要特點是:輕
Android DroidPlugin 插件化機制解析:免安裝執行 APK 的原理
DroidPlugin 是 Android 上的一種插件化機制,可在不安裝外掛 APK 的情況下執行外掛程式。其概念包括共享進程、占坑與 Hook。共享進程讓多個 APK