您的位置:首页 > 移动开发 > Android开发

android 图片缓存LruCache

2016-03-17 15:03 459 查看
异步加载图片的例子,网上也比较多,大部分用了HashMap<String, SoftReference<Drawable>> imageCache ,但是现在已经不再推荐使用这种方式了,因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,这让软引用和弱引用变得不再可靠。另外,Android 3.0 (API Level 11)中,图片的数据会存储在本地的内存当中,因而无法用一种可预见的方式将其释放,这就有潜在的风险造成应用程序的内存溢出并崩溃,所以我这里用得是LruCache来缓存图片,当存储Image的大小大于LruCache设定的值,系统自动释放内存,这个类是3.1版本中提供的,如果你是在更早的Android版本中开发,则需要导入android-support-v4的jar包(这里要注意咯)
注意:这仅仅是图片缓存,不包含网络下载与sd卡存储。

public class ImageCache {
LruCache<String,Bitmap> mImageCache;
public ImageCache(){
initImageCache();
};
private void initImageCache(){
final int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
final int cacheSize = maxMemory/4;
mImageCache = new LruCache<String,Bitmap>(cacheSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes()*value.getHeight()/1024;
}
};

}
public void put(String key, Bitmap bitmap){
mImageCache.put(key,bitmap);
}
public Bitmap get(String key){
return mImageCache.get(key);
}
}

1、内存

the maximum number of bytes the heap can expand to.


Runtime.getRuntime().maxMemory()
the number of bytes currently available on the heap without expanding the heap. See {@link #totalMemory} for the heap's current size. When these bytes are exhausted, the heap may expand. See {@link #maxMemory} for that limit.
Runtime.getRuntime().freeMemory()可用内存,是随时变化的
the number of bytes taken by the heap at its current size.
Runtime.getRuntime().totalMemory()

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: