简体   繁体   English

动态处理内存泄漏

[英]Handle memory leak dynamically

I know there are many discussions about memory leak/ handling memory leaks in android apps, but can it handled dynamically. 我知道在Android应用程序中有很多关于内存泄漏/处理内存泄漏的讨论,但是可以动态处理。

I just got this question in one of my interview. 我只是在一次采访中提出了这个问题。 The question was 问题是

How to detect memory leak when application is running on user's device and save the data before crash(OutOfMemoryError) . 当应用程序在用户设备上运行时,如何检测内存泄漏并在崩溃之前保存数据(OutOfMemoryError)。

I can guess till a BaseActivity, something like just make one BaseActivity for all Activities and save the data in onStop(). 我可以猜测到一个BaseActivity,就像为所有Activity创建一个BaseActivity并将数据保存在onStop()中。

I also can guess to extend Error class in the BaseActivity, but unfortunately java does not supports Multiple Inheritance and also there is no particular method in Error class to detect any errors dynamically AFAIK. 我还可以猜测要在BaseActivity中扩展Error类,但是不幸的是Java不支持Multiple Inheritance,并且Error类中没有特定的方法可以动态检测AFAIK的任何错误。

I might wrong in above cases. 在上述情况下我可能会错。

Is there any other way to do this ? 还有其他方法吗?

I would probably use the same approach as Leakcanary did. 我可能会使用与Leakcanary相同的方法。 You can read about it here . 你可以在这里阅读。

In short, they are creating weak references between objects. 简而言之,它们在对象之间创建了弱引用。 After GC they are checking if the reference is being cleared. GC之后,他们正在检查参考是否被清除。 If not they are dumping heap, and analyzing dump. 如果不是,他们正在倾销堆,并正在分析倾销。 Analyzer computes the shortest strong reference path to the GC Roots to determine if there is a leak, and then builds the chain of references causing the leak. 分析器计算到GC根的最短强引用路径,以确定是否存在泄漏,然后构建导致泄漏的引用链。 In that moment if leak is there you can save all data that you need. 在那一刻,如果有泄漏,您可以保存所需的所有数据。

Problem is that if you want to save all data you need to do all of this on main thread. 问题是,如果要保存所有数据,则需要在主线程上执行所有这些操作。 Otherwise, app can be closed, data can be lost etc. 否则,应用程序可能会关闭,数据可能会丢失等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM