package com.example.linux.lrucachetest;
import android.graphics.Bitmap;
import android.util.LruCache;
/**
* Created by huhx on 2016/4/12.
*/
public class ImageDownloader {
private static final String TAG = "TextDownload";
private LruCache<String, Bitmap> lruCache;
public ImageDownloader() {
long maxMemory = Runtime.getRuntime().maxMemory();
int cacheSize = (int) (maxMemory / 8);
lruCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
}
// 把Bitmap对象加入到缓存中
public void addBitmapToMemory(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
lruCache.put(key, bitmap);
}
}
// 从缓存中得到Bitmap对象
public Bitmap getBitmapFromMemCache(String key) {
Log.i(TAG, "lrucache size: " + lruCache.size());
return lruCache.get(key);
}
// 从缓存中删除指定的Bitmap
public void removeBitmapFromMemory(String key) {
lruCache.remove(key);
}
}
此博客展示了Android中使用LruCache进行图片缓存管理的代码。定义了ImageDownloader类,在其构造函数中初始化LruCache,还提供了将Bitmap加入缓存、从缓存获取Bitmap以及从缓存删除指定Bitmap的方法,实现对图片缓存的有效管理。

404

被折叠的 条评论
为什么被折叠?



