简体   繁体   中英

Handle memory leak dynamically

I know there are many discussions about memory leak/ handling memory leaks in android apps, but can it handled dynamically.

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) .

I can guess till a BaseActivity, something like just make one BaseActivity for all Activities and save the data in 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.

I might wrong in above cases.

Is there any other way to do this ?

I would probably use the same approach as Leakcanary did. 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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