在android應用開發過程中,經常使用LruCache<String, Bitmap> 對圖檔進行緩存,LruCache在清除bitmap時,并沒有将bitmap recycle。手動 recycle可能會報trying to use a recycled bitmap錯誤。
解決思路:在bitmap recycle時,判斷bitmap是否在使用。
mMemoryCache = new LruCache<String, Bitmap>(size) {
@Override
protected int sizeOf(String key, Bitmap bitmap){
return bitmap.getByteCount();
}
@Override
protected void entryRemoved(boolean evicted, String key,
Bitmap oldValue, Bitmap newValue) {
// TODO Auto-generated method stub
if(mContext instanceof Activity){
Activity activity =(Activity) mContext;
//通過bitmap查找與其關聯的view,找不到則認為沒有view在使用該bitmap
View view =activity.getWindow().getDecorView().findViewWithTag(oldValue);
if(view ==null && !oldValue.isRecycled()){
oldValue.recycle();
}
}
super.entryRemoved(evicted, key, oldValue, newValue);
}
};
private void refreshView(View view ,Bitmap bitmap){
if(view instanceof ImageView){
((ImageView) view).setImageBitmap(bitmap);
}else{
view.setBackgroundDrawable(new BitmapDrawable(bitmap));
}
//将bitmap與view關聯,以實作判斷bitmap是否在使用
view.setTag(bitmap);
}
private void refreshView(View view ,int res){
if(view instanceof ImageView){
((ImageView) view).setImageResource(res);
}else{
view.setBackgroundResource(res);
}
view.setTag(null);
}