如何追踪内存泄漏 - 查找实时引用
我有一个相当复杂的应用程序 -
UI Activity 启动一个服务并设置 2 路 AIDL 回调,以便两者可以进行通信。
该服务将永远运行(除非在 UI 活动中点击“关闭”按钮)。
问题是当用户退出Activity时,Activity内存并没有被释放。 - 即使 UI Activity 已关闭,我的应用程序使用的内存量也是相同的。 - 即使 UI Activity 已关闭,堆上仍然显示 mapTiles 和其他 UI 垃圾。
所以我的猜测是服务以某种方式保存了对活动的引用。我知道有很多文章警告有关泄漏活动上下文的信息。服务仅通过存储在应用程序范围内的弱引用来引用活动。 (扩展应用程序的类)
有什么方法可以找到具体引用活动的内容吗?支配树显示 mapTiles 和 ListView 布局耗尽了我所有的内存......但我找不到对保持这些东西存活的 Activity 的引用。
另外,如果发生 OutOfMemoryException,是否有办法转储 HPROF 堆转储内容?
I have a fairly complex app -
The UI Activity launches a Service and sets up 2 way AIDL callbacks so the two can communicate.
The service runs forever (unless hits 'off' button in UI Activity).
The problem is when the user exits the Activity, the Activity memory is not released.
-The amount of memory used by my app is the same even if the UI Activity has been closed.
-The heap still shows mapTiles and other UI crap on it even if the UI Activity has been closed.
So my guess is somehow the Service is holding references to the Activity. I know the many articles warning about leaking the Activity Context. The Service only references the Activity through a Weak Reference stored at Application scope. (a class that extends Application)
Is there any way to find what specifically is referencing the Activity? The dominator tree shows mapTiles and ListView layouts eating all my memory... but I can't find the reference to the Activity which is keeping that stuff alive.
Also, is there a way to dump an HPROF heap dump thing if OutOfMemoryException occurs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Android 中没有“退出 Activity”。调用 finish() 或按回活动不会从活动使用的内存中删除对象。 Android 本质上会在未来的某个随机时刻自行处理此问题。
如果您希望在活动结束时从内存中释放对象,您需要自己手动释放它们。
编辑:可用于查找内存使用情况的类是 活动管理器。
There is no "exit Activity" in Android. Calling finish() or pressing back on the activity does not remove objects from memory that the activity used. Android inherently takes care of this itself at some random point in the future.
If you want your objects to be released from memory at the moment the activity finishes, you need to manually release them yourself.
Edit: The class that can be used to find memory usage is the ActivityManager.
如果不是您自己持有引用(“通过存储在应用程序范围内的弱引用引用活动”,您会将其置空吗?我想知道为什么您引用服务中的活动,通常是另一种方式),您尝试过吗执行GC?只要还有足够的内存,就不会发生 gc 来移走垃圾。
If it's not yourself who is holding a reference ("references the Activity through a Weak Reference stored at Application scope", do you null it? I wonder why you reference the activity in the service, usually its the other way), did you try to execute a GC? As long as there is enough memory left, no gc will take place to move the trash away.