使用 LRU 快取的點陣圖快取

LRU 快取

以下示例程式碼演示了用於快取影象的 LruCache 類的可能實現。

private LruCache<String, Bitmap> mMemoryCache;

這裡字串值是點陣圖值的關鍵。

// Get max available VM memory, exceeding this amount will throw an
// OutOfMemory exception. Stored in kilobytes as LruCache takes an
// int in its constructor.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);

// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;

mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
    @Override
    protected int sizeOf(String key, Bitmap bitmap) {
        // The cache size will be measured in kilobytes rather than
        // number of items.
        return bitmap.getByteCount() / 1024;
    }
};

用於將點陣圖新增到記憶體快取

public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
        mMemoryCache.put(key, bitmap);
    }    
}

從記憶體快取中獲取點陣圖

public Bitmap getBitmapFromMemCache(String key) {
    return mMemoryCache.get(key);
}

要將點陣圖載入到 imageview,只需使用 getBitmapFromMemCache(Pass key)。