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()
相关文章推荐
- android五种布局模式
- 分享几个实用的Android开源项目(这是我摘抄的。。。o(╯□╰)o)
- Android Studio如何集成Genymotion
- Android开发笔记学习秘籍(十五)
- android 百度地图定位
- java降级后elipse的android项目无法运行
- android- 调试Error:more than one device and emulator
- 【Android开发】动画弹出PopupWindow并使背景变暗
- android开发 内部类 匿名内部类
- Android 代码设置密码输入框内容的显示/隐藏
- Android MVP模式的理解
- Android二级分类列表ListView
- Android.mk详解
- Android之最全,最经典,最无私的资源
- Android ListView自定义Adapter使用误区
- android布局练习
- Android四大组件之Service
- Android之自定义View的监听事件
- 阅读android项目源码
- android应用加速优化与分析,兼谈launcher优化。