Android缓存的一个Demo
2016-01-13 18:32
381 查看
Android加载多张图片容易出现oom异常,而用弱引用保存图片容易被系统回收。上网查了一些资料,自己写了一个强弱一起用的Demo,仅供产考。
代码:
代码:
import android.graphics.Bitmap; import android.support.v4.util.LruCache; import android.util.Log; import java.lang.ref.SoftReference; import java.util.LinkedHashMap; /** * 缓存图片的一个容器 * Created by yyw on 2016/1/6. */ public class BitmapCache { /**软引用缓存的集合大小**/ private static final int SOFT_CACHE_CAPACITY = 10; /**单例模式**/ private static volatile BitmapCache BITMAP_CACHE; /**Android提供的硬引用**/ private LruCache<String, Bitmap> mHardBitmapCache; private LinkedHashMap<String, SoftReference<Bitmap>> mSoftBitmapCache = new LinkedHashMap<String, SoftReference<Bitmap>>(SOFT_CACHE_CAPACITY , 0.75f, true){ /**是否删除旧的**/ @Override protected boolean removeEldestEntry(Entry<String, SoftReference<Bitmap>> eldest) { if (size() > SOFT_CACHE_CAPACITY){ return true; } return super.removeEldestEntry(eldest); } }; private BitmapCache() { int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); // 使用最大可用内存值的1/8作为缓存的大小。 int cacheSize = maxMemory / 8; mHardBitmapCache = new LruCache<String, Bitmap>(cacheSize) { @Override public int sizeOf(String key, Bitmap value) { return value.getRowBytes() * value.getHeight()/1024; } @Override protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) { Log.v("tag", "hard cache is full , push to soft cache"); //硬引用缓存区满,将一个最不经常使用的oldvalue推入到软引用缓存区 mSoftBitmapCache.put(key, new SoftReference<Bitmap>(oldValue)); } }; } public static BitmapCache getInstance() { if (BITMAP_CACHE == null) { synchronized (BitmapCache.class) { if (BITMAP_CACHE == null) { BITMAP_CACHE = new BitmapCache(); } } } return BITMAP_CACHE; } /** * 从缓冲当中获取图片 * @param key * @return */ public Bitmap getBitmap(String key){ synchronized(mHardBitmapCache){ final Bitmap bitmap = mHardBitmapCache.get(key); if(bitmap != null) return bitmap; } //硬引用缓存区间中读取失败,从软引用缓存区间读取 synchronized(mSoftBitmapCache){ SoftReference<Bitmap> bitmapReference = mSoftBitmapCache.get(key); if(bitmapReference != null){ final Bitmap bitmap2 = bitmapReference.get(); if(bitmap2 != null) return bitmap2; else{ Log.v("tag", "soft reference 已经被回收"); mSoftBitmapCache.remove(key); } } } return null; } //缓存bitmap public boolean putBitmap(String key, Bitmap bitmap){ if(bitmap != null){ synchronized(mHardBitmapCache){ mHardBitmapCache.put(key, bitmap); } return true; } return false; } }
相关文章推荐
- Android 仿转转商品详情页面图片消失方式
- Android View系统解析(下)
- Android View系统解析(上)
- AndroidStudio操作笔记--如何加载外部aar包
- Android应用签名打包(一)
- Android 创建其他程序对应的Context
- Android音乐播放器乱码
- Android之Activity的栈管理
- RxJava开发精要7 - Schedulers-解决Android主线程问题
- androidStudio 发布自己的jar
- android Asynctask 和Handler的优缺点
- Android Studio IDE Out of Memory
- Android RecyclerView中实现自定义GridView的方式(实现不同item)
- Android static 内存优化
- Android Studio中library工程生成jar
- Android:30分钟弄明白Touch事件分发机制
- Android ViewGroup事件分发机制
- Android串口通信:串口读写
- Android AsyncTask简介-知识点+代码
- 【Android事件的处理】---基于回调的事件处理