android: 缓存异步加载Bitmap

来源:互联网 发布:人工智能的弊端论文 编辑:程序博客网 时间:2024/05/18 00:41

step1:创建内存缓存

//采用内存缓存,速度快,占用内存

public class MemoryCache {
private static LruCache<String, Bitmap> cache;
private MemoryCache(){};
public static LruCache<String, Bitmap> getInstance(){
if(cache == null){
final int _maxMemory = (int)(Runtime.getRuntime().maxMemory()/1024);
final int _cacheSize = _maxMemory/8;
cache = new LruCache<String, Bitmap>(_cacheSize);
}
return cache;
}

public static void addBitmapToMemoryCache(String key,Bitmap bmp){
if(cache.get(key) == null)
cache.put(key, bmp);
}

public static Bitmap getBitmapFromCache(String key){
return cache.get(key);
}
}

step2:压缩Bitmap

public class BitmapCompress {
public static Bitmap Comperss(Resources res,int resId,int requestWidth,int requestHeight){
BitmapFactory.Options _options = new BitmapFactory.Options();
_options.inJustDecodeBounds = true;//不加载进内存
BitmapFactory.decodeResource(res, resId, _options);
int outWidth = _options.outWidth;
int outHeight = _options.outHeight;

int inSampleSize =1;
//计算压缩比例
while(outWidth/requestWidth >inSampleSize
&&outHeight/requestHeight>inSampleSize){
inSampleSize*=2;
}
_options.inSampleSize = inSampleSize;
//加载进内存
_options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, _options);
}
}

step3:异步加载Bitmap

public class LoadImageTask extends AsyncTask<Integer,Integer,Bitmap>{
private final WeakReference<ImageView> mImageViewReference;
private Context mContext;

public LoadImageTask(Context pContext,ImageView pImageView){
mContext = pContext;
mImageViewReference = new WeakReference<ImageView>(pImageView);
}

@Override
protected Bitmap doInBackground(Integer... params) {
Bitmap _bitmap = BitmapCompress.Comperss(mContext.getResources(), params[0], 200, 200);
//将_bitmap加入缓存中
MemoryCache.getInstance().put(String.valueOf(params[0]), _bitmap);
return _bitmap;
}

@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(mImageViewReference != null && result != null){
ImageView _imageview = mImageViewReference.get();
if(_imageview != null)
_imageview.setImageBitmap(result);
}
}
}

0 0
原创粉丝点击