android中使用SoftRefrence解决Bitmap过大内存溢出问题
来源:互联网 发布:mac版的qq截图快捷键 编辑:程序博客网 时间:2024/06/05 07:09
之前做一个手机展示多张图片的项目,做了一个异步加载图片并显示的独立控件,经常遇到报这种错误:java.lang.OutOfMemoryError: bitmap size exceeds VM budget,这是因为,android系统中读取位图Bitmap时.分给虚拟机中图片的堆栈大小只有8M。所以不管我使用了SD卡缓存图片,还是使用了bitmap.recycle()进行内存回收,但在控件多次加载后,还是经常会遇到这个内存溢出的问题。后来使用软引用(SoftRefrence)来进行内存缓存,这一问题得以解决。程序片段如下:
private final static int HARD_CACHE_CAPACITY = 30;/** * 缓存bitmap至内存 */private final HashMap<String, Bitmap> mHardBitmapCache = new LinkedHashMap<String, Bitmap>(HARD_CACHE_CAPACITY/ 2, 0.75f, true) {@Override protected boolean removeEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) { if (size() >HARD_CACHE_CAPACITY) { //当map的size大于30时,把最近不常用的key放到mSoftBitmapCache中,从而保证mHardBitmapCache的效率 mSoftBitmapCache.put(eldest.getKey(), new SoftReference<Bitmap>(eldest.getValue())); return true; } else return false; } }; /** *当mHardBitmapCache的key大于30的时候,会根据LRU算法把最近没有被使用的key放入到这个缓存中。 *Bitmap使用了SoftReference,当内存空间不足时,此cache中的bitmap会被垃圾回收掉 */ private final static ConcurrentHashMap<String, SoftReference<Bitmap>> mSoftBitmapCache = new ConcurrentHashMap<String,SoftReference<Bitmap>>(HARD_CACHE_CAPACITY / 2);/** * 从缓存中获取图片 */ private Bitmap getBitmapFromCache(String name) { // 先从mHardBitmapCache缓存中获取 synchronized (mHardBitmapCache) { final Bitmap bitmap = mHardBitmapCache.get(name); if (bitmap != null) { //如果找到的话,把元素移到linkedhashmap的最前面,从而保证在LRU算法中是最后被删除 mHardBitmapCache.remove(name); mHardBitmapCache.put(name,bitmap); return bitmap; } } //如果mHardBitmapCache中找不到,到mSoftBitmapCache中找 SoftReference<Bitmap>bitmapReference = mSoftBitmapCache.get(name); if (bitmapReference != null) { final Bitmap bitmap =bitmapReference.get(); if (bitmap != null) { return bitmap; } else { mSoftBitmapCache.remove(name); } } return null; }/** * 显示图片 * @param name 图片名称*/ private void show(String name){ImageView image = new ImageView(act);image.setImageBitmap(getBitmapFromCache(name));}
使用了上面的缓存后,图片展示速度提高了,而且不再出现内存溢出的问题了。
0 0
- android中使用SoftRefrence解决Bitmap过大内存溢出问题
- android中使用SoftRefrence解决Bitmap过大内存溢出问题
- android Bitmap过大内存溢出问题的解决
- 解决Android Bitmap内存溢出问题
- poi解决内存消耗过大溢出问题
- 解决读取bitmap内存溢出问题
- 解决Bitmap导致的内存溢出问题
- Android使用bitmap导致内存溢出(oom)问题
- android解决bitmap内存溢出之二
- android中使用bitmap时防止内存溢出
- android中使用bitmap时防止内存溢出
- android中使用bitmap时防止内存溢出
- Android---加载图片 解决图片过大导致的内存溢出问题
- 解决 SqlServer执行脚本,文件过大,内存溢出问题
- Android Bitmap 内存溢出的问题
- Bitmap内存溢出问题
- android中Bitmap导致的内存溢出
- Android Bitmap内存管理,解决内存溢出问题(1)之自定义BitmapDrawable
- OCP 1Z0 052 116
- session失效,使用ajax请求数据被拦截,此时正常的处理逻辑是跳到登录界面,而不是界面没有变化(java判断是否是ajax请求)
- win7的UPnP如何打开/关闭
- 安卓系统下访问Web Service 的知识总结
- testing and SQA_动态白盒测试
- android中使用SoftRefrence解决Bitmap过大内存溢出问题
- [转]右键点击树控件的一项时候GetSelectedItem获取值错误问题
- PB窗口居中的实现方法
- MySQL [Err] 1215
- MyEclipse 常用快捷键
- LeetCode 73 Set Matrix Zeroes
- Oracle 创建表分区
- 0002/1000 你好上海
- 51单片机基础汇总