【发布时间】:2020-01-07 15:23:10
【问题描述】:
我有两个活动:MainActivity 和 Activity2。
MainActivity 只是通过 Intent 打开秒一个。
要从Activity2 返回MainActivity,我按下“返回”按钮。
当我执行这些步骤时,应用程序崩溃:
- 打开App:出现
MainActivity - 启动 Intent:
Activity2出现 - 按下“返回”按钮:
MainActivity出现 - 启动
Intent:我的应用程序因为这个错误而崩溃:IllegalArgumentException:无法绘制回收位图
MainActivity.java:
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
Activity2.java:
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
protected void onDestroy() {
super.onDestroy();
for(Map.Entry<Integer, ImageView> entry : mapImageViews.entrySet()) {
ImageView imageView = entry.getValue();
Drawable drawable = imageView.getDrawable();
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
if(bitmap != null) {
bitmap.recycle();
}
bitmapDrawable = null;
bitmap = null;
}
imageView.setOnClickListener(null);
imageView.setImageDrawable(null);
imageView.setImageBitmap(null);
imageView = null;
drawable = null;
}
mapImageViews.clear();
mapImageViews = null;
}
由于应用程序使用高分辨率图像(已与BitmapFactory 和inSampleSize 适配),为了避免内存泄漏,我在onDestroy() 方法中调用recycle()。
正如我通过阅读大量 SO 答案和在网络上了解到的那样,在位图上调用 recycle() 可以让它们尽早被垃圾收集。
但许多其他帖子建议不要调用 recycle(),或者至少建议仅在您确定 Activity 中不再需要位图时才这样做,即在 onDestroy() 方法中。
现在我有点担心我学到了什么,因为如果我删除 recycle(),错误就不会再发生了。
错误发生在装有 Android 4.4.2 的设备上,但不会发生在装有 Android 6.0 和 Nexus 7 (Android 5.1.1) 的设备上。
- 活动堆栈有问题吗?
- GC 是否试图释放位图的内存为时已晚?在这种情况下,如何彻底销毁 Activity 及其所有内容?
- 这两个 Android 版本有什么区别吗?
- 还是有什么我遗漏/错误的地方?
【问题讨论】:
-
你试过我下面给出的答案了吗?
-
如果
mapImageViews不是静态的,那么将所有内容归零是没有意义的,更像是货物崇拜而不是实际的清理。 -
@Miha_x64 你能更好地解释你的评论吗?
标签: java android exception bitmap garbage-collection