background

A few days ago, I wrote an article about several common Android memory leak problems and solutions. If you haven’t read it, you can also read it first. So how do we analyze and detect memory leaks when we actually have an unknown problem?

Memory leak detection tool

Use MAT to analyze memory leaks

Let’s start with the simplest example of a memory leak

public class MainActivity extends Activity { private static Context sContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sContext = this; }}Copy the code

1. First let’s start GC manually and then check Dump







Android-Monitors.png


I found that the latest AndroidStudio does not contain the hprof file, but there is one in tools for Monitors. If you open the following interface, you can also export the hprof file





image.png


The exported files are not directly recognized by MAT and need to be converted by the hprof-conv command, which is a tool provided by the Android SDK under the plafrom-tools directory

Hprof -conv com.aotuman.leak.hprof(original file) com.aotuman.leak.hprof(output file)Copy the code

Then we can use MAT to open files for memory analysis:





image.png


Histogran and Dominator Tree are the two main types of buffers used by MAT. Histogran and Dominator Tree are the two main types of buffers. Memory leak analysis is done by sorting objects in memory in order from largest to smallest, and analyzing references between objects. The following two images are their interfaces:





Histogran.png




Dominator Tree.png

So how do we actually check for a memory leak? For example, in our Demo we probably know that MainActivity is causing a memory leak, so we can search, Then view his references as shown below (see both the Histogram and Dominator_Tree screens) :







image.png


After checking, we should see this screen:





image.png


As you can see from the figure, it is sContext that causes the memory leak.

Use LeakCanary to check for memory leaks

This way is relatively simple and intuitive, when there is a memory leak, it will prompt you between the chain of references that caused the memory leak. It’s easy to use:





LeakCancary.png


Here is a reminder on your phone that pops up in the notification bar after a memory leak occurs.







image.png


Is it very simple and clear, do not need our own analysis and search, as long as you are during the memory leak it will prompt you. Of course, if you want to further study the students can go to Google, check its source code, analysis of the implementation principle, here will not expand.

conclusion

All in all, memory leakage is a relatively complex problem, but as long as we master certain skills, it is also very simple to solve.