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

Android 图片缓存之内存缓存技术LruCache

2016-02-27 19:14 621 查看
转自:http://blog.chinaunix.net/uid-26930580-id-4138306.html
在Android中,有一个叫做LruCache类专门用来做图片缓存处理的。

它有一个特点,当缓存的图片达到了预先设定的值的时候,那么近期使用次数最少的图片就会被回收掉。

步骤:(1)要先设置缓存图片的内存大小,我这里设置为手机内存的1/8,

手机内存的获取方式:int
MAXMEMONRY = (int) (Runtime.getRuntime() .maxMemory() / 1024);

(2)LruCache里面的键值对分别是URL和对应的图片

(3)重写了一个叫做sizeOf的方法,返回的是图片数量。

private LruCache<String, Bitmap> mMemoryCache;

private LruCacheUtils() {

if (mMemoryCache == null)

mMemoryCache = new LruCache<String, Bitmap>(

MAXMEMONRY / 8) {

@Override

protected int sizeOf(String key, Bitmap
bitmap) {

// 重写此方法来衡量每张图片的大小,默认返回图片数量。

return bitmap.getRowBytes() * bitmap.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");

}

};

}

(4)下面的方法分别是清空缓存、添加图片到缓存、从缓存中取得图片、从缓存中移除。

移除和清除缓存是必须要做的事,因为图片缓存处理不当就会报内存溢出,所以一定要引起注意。

public void clearCache() {

if (mMemoryCache != null) {

if (mMemoryCache.size() > 0) {

Log.d("CacheUtils",

"mMemoryCache.size() " + mMemoryCache.size());

mMemoryCache.evictAll();

Log.d("CacheUtils", "mMemoryCache.size()" + mMemoryCache.size());

}

mMemoryCache = null;

}

}

public synchronized void addBitmapToMemoryCache(String key, Bitmap
bitmap) {

if (mMemoryCache.get(key) == null) {

if (key != null && bitmap != null)

mMemoryCache.put(key, bitmap);

} else

Log.w(TAG, "the
res is aready exits");

}

public synchronized Bitmap getBitmapFromMemCache(String key) {

Bitmap bm = mMemoryCache.get(key);

if (key != null) {

return bm;

}

return null;

}

/**

* 移除缓存

*

* @param key

*/

public synchronized void removeImageCache(String key) {

if (key != null) {

if (mMemoryCache != null) {

Bitmap bm = mMemoryCache.remove(key);

if (bm != null)

bm.recycle();

}

}

}

4、两者的比较

说到这里,我觉得有必要来进行一下比较了。

网上有很多人使用软引用加载图片的多 ,但是现在已经不再推荐使用这种方式了,

(1)因为从 Android 2.3 (API Level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,

这让软引用和弱引用变得不再可靠。

(2)另外,Android 3.0 (API Level 11)中,图片的数据会存储在本地的内存当中,

因而无法用一种可预见的方式将其释放,这就有潜在的风险造成应用程序的内存溢出并崩溃,

所以我这里用得是LruCache来缓存图片,当存储Image的大小大于LruCache设定的值,系统自动释放内存,

这个类是3.1版本中提供的,如果你是在更早的Android版本中开发,则需要导入android-support-v4的jar包。

补充:

添加bitmap到文件缓存



当内存缓存中没有该bitmap时,从文件缓存获取bitmap,再加入内存缓存



添加Bitmap到内存缓存



从内存缓存中获取Bitmap

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