Bitmap回收异常:trying to use a recycled bitmap android.graphics.Bitmap问题解决

在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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值