内存缓存技术:android.util.LruCache
1、在Android中,有个类LruCache专门用来做图片缓存处理的。它的特点是:当缓存的图片达到了预定设定的值得时候,那么近期使用次数最少的图片将会被回收掉。
2、步骤
(1)要先设置缓存图片的内存大小。
手机内存的获取方式:int MaxMemory = (int) Runtime.getRuntime().maxMemory();
(2)LruCache里面的键值是URL;
(3)重写一个 sizeof() 的方法。
3、关键代码如下:
package com.example.demo;
import android.graphics.Bitmap;
import android.util.Log;
import android.util.LruCache;
public class LruCacheUtils {
private String TAG = "LruCacheUtils";
//应用程序可获取的最大内存,除以1024是以KB为单位
private int MaxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
private LruCache<String, Bitmap> mMemoryCache;
//创建缓存
public void CreateCache(){
if(mMemoryCache == null){
//使用最大可用内存的1/8最为缓存大小
mMemoryCache = new LruCache<String, Bitmap>(MaxMemory/8){
@Override
protected int sizeOf(String key, Bitmap bitmap) {
// TODO Auto-generated method stub
//重写此方法用了衡量每张图片的大小,默认返回的是图片的数量
return bitmap.getByteCount()/1024;
}
};
}
}
//清空缓存
public void cleanCache(){
if(mMemoryCache != null){
if(mMemoryCache.size() > 0){
Log.d(TAG, "mMemoryCache.size() " + mMemoryCache.size());
mMemoryCache.evictAll();
Log.d(TAG, "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 ready exits");
}
}
}
//从缓存中取得图片
public synchronized Bitmap getBitmapFromMemCache(String key){
Bitmap bitmap = mMemoryCache.get(key);
if(key != null){
return bitmap;
}
return null;
}
//从缓存中移除图片
public synchronized void removeImageCache(String key){
if(key != null){
if(mMemoryCache != null){
Bitmap bitmap = mMemoryCache.remove(key);
if(bitmap != null){
bitmap.recycle();
}
}
}
}
}
4、 当向ImageView中加载一张图片时,首先会在LruCache的缓存中进行检查。如果查到了相应的键值则会立即更新ImageView,否则开启一个新的线程来加载这张图片。代码例子如下:
public void loadBitmap(int resId, ImageView imageView) {
final String imageKey = String.valueOf(resId);
final Bitmap bitmap = getBitmapFromMemCache(imageKey);
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageResource(R.drawable.image_placeholder);
BitmapWorkerTask task = new BitmapWorkerTask(imageView);
task.execute(resId);
}
}
转载:http://blog.chinaunix.net/uid-26930580-id-4138306.html