1、初学者可以将Lru缓存理解成一个Map集合,底层是LinkedHashMap。特点:以空间换时间
使用步骤:
(1)创建对象
(2)保存对象进内存
(3)取出目标对象
public void method() {
int maxMemory = (int) Runtime.getRuntime().maxMemory(); // 获取设备的最大内存
int cacheSize = maxMemory / 4; // 一版设置缓存为内存的1/4
mCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) { // 每次有内容进缓存,都会调用此方法
return value.getByteCount(); // 返回该对象的大小,告知内存管理器
}
};
}
public void addBitmapToCache(String url, Bitmap value) {
if (getBitmapFromCache(url) == null)
mCache.put(url, value);
}
public Bitmap getBitmapFromCache(String url) {
return mCache.get(url);
}
只需要在合适的位置调用上述两个方法即可