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

关于Canvas: trying to use a recycled bitmap android.graphics的疑惑

2014-09-30 15:51 423 查看
====================问题描述====================
因为viewpager图片内存溢出的问题,不得不考虑手动释放内存,不过出的问题我不理解。

我的想法是创建一个Map,然后用instantiateItem中的参数arg0当作键,bitmap当作值,当destroyItem中去掉VIew的时候我捎带着把不再用到的bitmap也回收掉
//这个是存bitmap的map
public HashMap<Integer, SoftReference<Bitmap>> cacheBit;

adapter中大概的相关代码是这样的:

//这个是destroyItem中回收代码
// 这里进行回收,当我们左右滑动的时候,会把早期的图片回收掉.
public void destroyItem(View arg0, int arg1, Object arg2) {
// TODO Auto-generated method stub
View view = (View) arg2;
((ViewPager) arg0).removeView(view);
//回收图片的代码
if (cacheBit.containsKey(arg1)) {
try {
Bitmap bm = cacheBit.get(arg1).get();
if (null != bm && !bm.isRecycled()) {
bm.recycle();
bm = null;
}
// 提醒系统回收图片
System.gc();
} catch (Exception e) {
// TODO: handle exception
System.out.println("图片已被回收");
}

cacheBit.remove(arg1);
}
}

//然后这个是加载view的页面,在这个方法中我将bitmap存入map中,方便回收:
public Object instantiateItem(View arg0, int arg1) {
// TODO Auto-generated method stub
//这一部分是不相关的代码
View view;
LayoutInflater inflater = LayoutInflater.from(context);
view = inflater.inflate(R.layout.headingline_slider, null);
relative = (RelativeLayout) view.findViewById(R.id.bg);

//这里是图片的异步加载
// 根据图片URL去查找内存缓存有没有对应的Bitmap对象,并传递回调方法,如果没有,则等下载完毕回调
Bitmap bitmap = ImageLoader.loadBitmap(relative, list.get(arg1), new ImageCallBack() {
@Override
public void imageLoad(RelativeLayout relative, Bitmap bitmap) {
// TODO Auto-generated method stub
relative.setBackgroundDrawable(new BitmapDrawable(bitmap));
}
});
if (bitmap == null) {
relative.setBackgroundDrawable(new BitmapDrawable(bt));
} else {
relative.setBackgroundDrawable(new BitmapDrawable(bitmap));
}

// 将bitmap加载到map中,方便用过之后回收掉
cacheBit.put(arg1, new SoftReference<Bitmap>(bitmap));

((ViewPager) arg0).addView(view);
return view;
}

逻辑上我不知道哪里的错误,但是结果执行出来滑几次以后就会报一个异常,说我试图使用已回收的图片,不理解
Canvas: trying to use a recycled bitmap android.graphics.Bitmap@4054d588
====================解决方案1====================
如果有相同的url 你要控制图片的引用计数 只有为0 你才能回收。
====================解决方案2====================
Bitmap bitmap = ImageLoader.loadBitmap(relative, list.get(arg1), new ImageCallBack() {
@Override
public void imageLoad(RelativeLayout relative, Bitmap bitmap) {
// TODO Auto-generated method stub
relative.setBackgroundDrawable(new BitmapDrawable(bitmap));
}
});
if (bitmap == null) {
relative.setBackgroundDrawable(new BitmapDrawable(bt));
} else {
relative.setBackgroundDrawable(new BitmapDrawable(bitmap));
}

// 将bitmap加载到map中,方便用过之后回收掉
cacheBit.put(arg1, new SoftReference<Bitmap>(bitmap));

/
这里 你有可能将bitmap=null 缓存进cache中。
//初始化时候 你的 bitmap 必然 为null ,但是你依然将这个null 写入缓存

====================解决方案3====================
根据代码看,你应该是使用ImageLoader 这个第三方的工具,
基本上比较完善的工具都会提供图片缓存机制,并有比较完善的淘汰算法。
当你的item摧毁时候,你recyle bitmap,但是对于imageLoader 它不知这个图片recycle了,就有可能同样的url 他返回的还是这个recycled 的图片。

你检查下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐