一般网上Bitmap的缓存方法都是采用软引用的方式,其实还有更好的方法,这也是Google官方推荐的方法。废话不说,放代码。
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
/**
* Created by Cying on 14-2-21.
*/
public class BitmapCache {
public static BitmapCache instance;
public static BitmapCache getInstance() {
if (instance == null) {
instance = new BitmapCache();
}
return instance;
}
private LruCache<String, Bitmap> mImageCache;
private BitmapCache() {
// 获取到可用内存的最大值,使用内存超出这个值会引起OutOfMemory异常。
// LruCache通过构造函数传入缓存值,以KB为单位。
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// 使用最大可用内存值的1/8作为缓存的大小。
int cacheSize = maxMemory / 8;
mImageCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// 重写此方法来衡量每张图片的大小,默认返回图片数量。
return ImageHelper.getByteCount(bitmap) / 1024;
}
};
}
public void addBitmapToCache(String path, Bitmap bitmap) {
if(getBitmapByPath(path)!=null)
{
mImageCache.remove(path);
}
mImageCache.put(path, bitmap);
}
public Bitmap getBitmapByPath(String path) {
return mImageCache.get(path);
}
public void removeBitmap(String path)
{
Bitmap bitmap=getBitmapByPath(path);
if(bitmap!=null&&!bitmap.isRecycled())
{
bitmap.recycle();
}
mImageCache.remove(path);
}
}