安卓内存泄漏

发布于 2024-12-11 17:14:31 字数 877 浏览 0 评论 0原文

我一直在阅读有关 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

后eg是否自 2024-12-18 17:14:31

我仍然不明白一件事:如果 Drawable 没有声明为
static,为什么它没有在 Activity 的 onDestroy() 方法中销毁?
Drawable被破坏,TextView被破坏,Activity被破坏 -
没有引用,也没有内存泄漏。这不是应该的吗
工作?

是的,这就是它应该如何工作,但它们可能不会在 onDestroy() 中立即销毁。无法预测垃圾收集器运行的确切时间。有很多事情会触发这一点。例如,如果您的应用程序在允许的堆内存上运行不足,或者其他应用程序正在尝试分配更多内存...

如果您希望立即销毁位图,您应该调用 Bitmap.recycle() 。

此视频解释了 GC 如何运行以及有关 Android 内存管理的许多其他有用信息:

http:// /www.youtube.com/watch?v=_CruQY55HOk

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?

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文