安卓内存泄漏
我一直在阅读有关 Android 内存泄漏的文章。在我的应用程序中,我遇到了 java.lang.OutOfMemoryError: 位图大小超出 VM 预算 异常。当我用谷歌搜索时,我发现这是一个常见错误(this SO问题和这个问题处理问题),我使用了建议的解决方案。
我找到了处理该问题的官方 Android 文档和SO问题解释官方示例。它在示例中说:
drawable 有一个对 TextView 的引用,它本身有一个 对活动(上下文)的引用,而该活动又具有引用 几乎任何事情
我仍然不明白一件事:如果 Drawable 没有声明为静态,为什么它没有在 Activity 的 onDestroy() 方法中销毁? Drawable 被销毁,TextView 被销毁,Activity 被销毁——没有引用,也没有内存泄漏。这不是它应该如何工作的吗?
I've been reading about memory leaks in Android. In my application, I was getting java.lang.OutOfMemoryError: bitmap size exceeds VM budget
exception. As I googled it, I found it to be a common error (this SO question and this SO question deal with the problem) and I used a suggested solution.
I found an official Android documentation dealing with the issue and SO question explaining the official example. It says in the example:
the drawable has a reference to the TextView which itself has a
reference to the activity (the Context) which in turns has references
to pretty much anything
I still don't understand one thing: if Drawable isn't declared as static, why isn't it destroyed in activity's onDestroy()
method? Drawable is destroyed, TextView is destroyed, Activity is destroyed - no references and no memory leaks. Isn't it how it is supposed to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这就是它应该如何工作,但它们可能不会在
onDestroy()
中立即销毁。无法预测垃圾收集器运行的确切时间。有很多事情会触发这一点。例如,如果您的应用程序在允许的堆内存上运行不足,或者其他应用程序正在尝试分配更多内存...如果您希望立即销毁位图,您应该调用 Bitmap.recycle() 。
此视频解释了 GC 如何运行以及有关 Android 内存管理的许多其他有用信息:
http:// /www.youtube.com/watch?v=_CruQY55HOk
Yes, that is how it supposed to work but they might not be immediately destroyed in
onDestroy()
. Exact time when Garbage Collector will run cannot be predicted. There are many things that trigger that. For example if your application is running low on allowed heap memory or if some other application is trying to allocate more memory...If you want your bitmap to be destroyed immediately you should call
Bitmap.recycle()
.How GC runs, and many other useful information about memory management in android are explained in this video:
http://www.youtube.com/watch?v=_CruQY55HOk