The target

Most of the articles on the web are about the use of Profile, which can help you detect memory leaks and whose memory leaks you have. However, according to the article to locate who caused the leak, I have not found a method. Through several efforts, I found an easy path, hoping to be helpful to other friends

reference

GithubDemo click on a simple example -> Memory leak -> and return to the previous page to complete the leak simulation

steps

  • Simulate a memory leak yourself
  • Use profilers to locate memory leaks

Simulated memory leak

Define a static variable of the context in the TestActivity class. OnCreate assigns this variable to the current Activity context. When you fall back to the previous page, the TestActivity cannot be released because static variables are held, causing a memory leak

Use profilers to accomplish positioning

First complete the Dump collection

First we lift the TestActivity and then we go back to the previous page, at which point there should be no TestActivity in memory; if there is, then there is a memory leak. Then complete a dump collection according to the following figure

Click 3 to enter the image below

Click 1 to collect GC memory and select dump file

Profiler analyzes memory leaks based on dump files. Skip to the following figure.

1. Indicates that there are several memory leaks

2. Check the current memory leak object, we can first focus on the memory leak of our own project.

3. Is an instance of an object, which may have multiple leak objects

4. Quote

5. After clicking 5,6 can easily locate what variable is causing the memory leak of this object.

It is easy to see from the following figure that the problem was caused by the static variable reference we located.