import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
/**
* 内存缓存 从内存读取数据速度是最快的,为了更大限度使用内存,这里使用了两层缓存。 硬引用缓存不会轻易被回收,用来保存常用数据,不常用的转入软引用缓存。
*
*/
public class ImageMemoryCache {
/**
* 软引用缓存容量
*/
private static final int SOFT_CACHE_SIZE = 15;
/**
* 硬引用缓存
*/
private static LruCache<String, Bitmap> mLruCache;
/**
* 软引用缓存
*/
private static LinkedHashMap<String, SoftReference<Bitmap>> mSoftCache;
public ImageMemoryCache(int cacheSize) {
// 初始化强引用缓存
if (mLruCache == null) {
mLruCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
if (value != null) {
// Bitmap所占用的内存空间数等于Bitmap的每一行所占用的空间数乘以Bitmap的行数
return value.getRowBytes() * value.getHeight();
} else {
return 0;
}
}
@Override
protected void entryRemoved(boolean evicted, String key,
Bitmap oldValue, Bitmap newValue) {
if (oldValue != null) {
// 硬引用缓存容量满的时候,会根据LRU算法把最近没有被使用的图片转入此软引用缓存
mSoftCache.put(key, new SoftReference<Bitmap>(oldValue));
}
}
};
}
// 初始化软引用缓存
if (mSoftCache == null) {
/**
* 第一个参数是初始化容器大小,第二个参数是负载因子,当容器被占用了75%的时候就增加空间,第三个参数设为true,
* 那么链接哈希映像将使用访问顺序而不是插入顺序来迭代各个映像
*/
mSoftCache = new LinkedHashMap<String, SoftReference<Bitmap>>(
SOFT_CACHE_SIZE, 0.75f, true) {
private static final long serialVersionUID = 6040103833179403725L;
@Override
protected boolean removeEldestEntry(
Entry<String, SoftReference<Bitmap>> eldest) {
// 返回true,指定插入元素时移除最老的元素
if (size() > SOFT_CACHE_SIZE) {
return true;
}
return false;
}
};
}
}
/**
* 从缓存中获取图片
*/
public Bitmap getBitmap(String url) {
Bitmap bitmap;
// 先从硬引用缓存中获取
synchronized (mLruCache) {
bitmap = mLruCache.get(url);
}
if (bitmap != null) {
return bitmap;
}
// 如果硬引用缓存中找不到,到软引用缓存中找
synchronized (mSoftCache) {
SoftReference<Bitmap> bitmapReference = mSoftCache.get(url);
if (bitmapReference != null) {
bitmap = bitmapReference.get();
if (bitmap != null) {
// 将图片移回硬缓存
mLruCache.put(url, bitmap);
mSoftCache.remove(url);
return bitmap;
} else {
mSoftCache.remove(url);
}
}
}
return null;
}
/**
* 添加图片到缓存
*/
public void saveBitmap(String url, Bitmap bitmap) {
if (bitmap != null) {
synchronized (mLruCache) {
mLruCache.put(url, bitmap);
}
}
}
public void clearCache() {
mSoftCache.clear();
}
}
图片内存缓存
最新推荐文章于 2024-07-24 19:05:28 发布