android.util.LruCache<K, V> 基於 LRU(最近最少使用)演算法,自動淘汰最久未訪問項目,適合記憶體敏感場景。
public class BitmapLruCache extends LruCache<String, Bitmap> {
public BitmapLruCache(int maxSizeKB) {
super(maxSizeKB * 1024); // 單位:Byte
}
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount(); // API 12+ 可用 getAllocationByteCount()
}
}
// 使用
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
int cacheSize = maxMemory / 8; // 佔 1/8 記憶體
BitmapLruCache cache = new BitmapLruCache(cacheSize);
cache.put(url, bitmap);
Bitmap bm = cache.get(url);
DiskLruCache 實現兩級緩存(記憶體 + 磁碟)。recycle() 不再使用的 Bitmap。