Android缓存的一个Demo
16lz
2022-01-12
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; }}
更多相关文章
- WebView中调用系统相册或拍照上传
- android TextView和EditText中显示图片
- Android图片堆叠效果实现
- android 动态向Gallery中添加图片及倒影&&3D效果
- Android(安卓)控件之Gallery图片集
- Android(安卓)SDK content Loader has encountered a problem.pa
- Android中屏幕密度和图片大小的关系分析
- Android异步加载图片,并缓存到SD卡
- Android(安卓)实现缩小图片像素