android 缓存Bitmap 使用内存缓存

时间:2021-09-06 21:36:23
private LruCache<String, Bitmap> mMemoryCache;
    /**
* 判断内存大小 设置位图的缓存空间
*/
private void judgeMemory() {
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8; mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
return bitmap.getByteCount() / 1024;
}
};
}
    /**
* 将位图添加到缓存中
*
* @param key key值
* @param bitmap 放入的位图
*/
private void addBitmapToMemoryCache(String key, Bitmap bitmap) {
if (getBitmapFromMemCache(key) == null) {
mMemoryCache.put(key, bitmap);
}
}
    /**
* 从缓存中得到位图
*
* @param key key值
* @return 返回取出的位图
*/
private Bitmap getBitmapFromMemCache(String key) {
return mMemoryCache.get(key);
}
    /**
* 检索AsyncTask是否已经被分配到指定的ImageView:
*
* @param imageView 传入imageview控件
* @return 返回已经被分配指定的imageview
*/
private static BitmapWorkTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getBitmapWorkTask();
}
}
return null;
}
    /**
* 创建一个专用的Drawable的子类来储存任务的引用。
*/
class AsyncDrawable extends BitmapDrawable {
private final WeakReference bitmapWorkerTaskReference; public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkTask bitmapWorkTask) {
super(res, bitmap);
bitmapWorkerTaskReference = new WeakReference(bitmapWorkTask);
} public BitmapWorkTask getBitmapWorkTask() {
return (BitmapWorkTask) bitmapWorkerTaskReference.get();
}
}

在doInBackground中添加到缓存

        protected Bitmap doInBackground(Integer... integers) {
final Bitmap bitmap = decodeSampleBitmapFromResources(getResources(), integers[0], 100, 100);
addBitmapToMemoryCache(String.valueOf(integers[0]), bitmap);
return bitmap;
}

然后在oncreate中 加载,首先判断从缓存中加载。

if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
final BitmapWorkTask task = new BitmapWorkTask(imageView);
final AsyncDrawable asyncDrawable = new AsyncDrawable(getResources(), decodeSampleBitmapFromResources(getResources(), resId, imageView.getMaxWidth(), imageView.getMaxHeight()), task);
imageView.setImageDrawable(asyncDrawable);
task.execute(resId);
}