1 定义:
private LruCache<String, Bitmap> mMemoryCache;
2 初始化:
public void initmem(){
//获取系统分配给每个应用程序的最大内存,每个应用系统分配32M
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int mCacheSize = maxMemory / 8;
//给LruCache分配1/8 4M
mMemoryCache = new LruCache<String, Bitmap>(mCacheSize){
//必须重写此方法,来测量Bitmap的大小
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
// fileUtils = new FileUtils(context);
}
3 在内存中查找
final String subUrl = url.replaceAll("[^\\w]", "");
// Bitmap bitmap = showCacheBitmap(subUrl);
if (mMemoryCache.get(subUrl)!=null)
{
bitmap= mMemoryCache.get(subUrl);
}
else
{
byte[] bitmapBytes = new FlickrFetchr().getUrlBytes(url);
// final Bitmap bitmap = BitmapFactory
// .decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
bitmap = BitmapFactory
.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
Log.i(TAG,"Bitmap created");
mMemoryCache.put(subUrl, bitmap);
//
}
4 释放:
this.mMemoryCache.evictAll(); //释放LruCache的缓存