android中使用SoftRefrence解决Bitmap过大内存溢出问题
来源:互联网 发布:网络牛牛怎么作弊 编辑:程序博客网 时间:2024/06/05 03:30
之前做一个手机展示多张图片的项目,做了一个异步加载图片并显示的独立控件,经常遇到报这种错误:java.lang.OutOfMemoryError: bitmap size exceeds VM budget,这是因为,android系统中读取位图Bitmap时.分给虚拟机中图片的堆栈大小只有8M。所以不管我使用了SD卡缓存图片,还是使用了bitmap.recycle()进行内存回收,但在控件多次加载后,还是经常会遇到这个内存溢出的问题。后来使用软引用(SoftRefrence)来进行内存缓存,这一问题得以解决。程序片段如下:
privatefinalstatic int HARD_CACHE_CAPACITY = 30;/** * 缓存bitmap至内存 */privatefinalHashMap<String, Bitmap> mHardBitmapCache = newLinkedHashMap<String, Bitmap>(HARD_CACHE_CAPACITY/ 2,0.75f,true) { @Override protectedbooleanremoveEldestEntry(LinkedHashMap.Entry<String, Bitmap> eldest) { if(size() >HARD_CACHE_CAPACITY) { //当map的size大于30时,把最近不常用的key放到mSoftBitmapCache中,从而保证mHardBitmapCache的效率 mSoftBitmapCache.put(eldest.getKey(),newSoftReference<Bitmap>(eldest.getValue())); returntrue; }else returnfalse; } }; /***当mHardBitmapCache的key大于30的时候,会根据LRU算法把最近没有被使用的key放入到这个缓存中。*Bitmap使用了SoftReference,当内存空间不足时,此cache中的bitmap会被垃圾回收掉*/privatefinalstatic ConcurrentHashMap<String, SoftReference<Bitmap>> mSoftBitmapCache = newConcurrentHashMap<String,SoftReference<Bitmap>>(HARD_CACHE_CAPACITY / 2); /*** 从缓存中获取图片 */privateBitmap getBitmapFromCache(String name) { // 先从mHardBitmapCache缓存中获取 synchronized(mHardBitmapCache) { finalBitmap bitmap = mHardBitmapCache.get(name); if(bitmap != null) { //如果找到的话,把元素移到linkedhashmap的最前面,从而保证在LRU算法中是最后被删除 mHardBitmapCache.remove(name); mHardBitmapCache.put(name,bitmap); returnbitmap; } } //如果mHardBitmapCache中找不到,到mSoftBitmapCache中找 SoftReference<Bitmap>bitmapReference = mSoftBitmapCache.get(name); if(bitmapReference != null) { finalBitmap bitmap =bitmapReference.get(); if(bitmap != null) { returnbitmap; }else{ mSoftBitmapCache.remove(name); } } returnnull;} /*** 显示图片 * @param name 图片名称*/privatevoidshow(String name){ ImageView image = newImageView(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
- SharePoint 2010 自定义字段开发
- 循环-16. 猴子吃桃问题(15)
- LeetCode: Maximum Depth of Binary Tree [104]
- LeetCode: Construct Binary Tree from Preorder and Inorder Traversal [105]
- 个人职业规划
- android中使用SoftRefrence解决Bitmap过大内存溢出问题
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal [106]
- PMP(项目管理专业人士资格认证)
- wxWidgets+wxSmith版电子词典
- 对 Android 开发者有益的 40 条优化建议
- 帝国cms所在位置[!--newsnav--]在哪里修改?
- 当生活很艰难,你想要放弃的时候,请记住,生活充满了起起落落,如果没有低谷,那站在高处也失去了意义
- bfgtcnhgvn
- 浅谈Swift语法