使用 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)。