您的位置:首页 > 移动开发 > Android开发

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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: