Use Android studio to detect memory leaks (leakcanary)

Memory leakage is the biggest headache for Android developers. Perhaps a small memory leak may be an ant nest that destroys the Bank of thousands of miles. How can I detect a memory leak? The memory console (display) in Android Studio provides a memory monitor. We can easily view the performance and memory usage of the application through it, so that we can find the objects that need to be released, find memory leaks, etc.

Familiar with memory interface

Open the log console and there is a label memory. We can analyze the memory used by the current program in this interface.

After running the app to be monitored, open the Android monitor console window to see the memory console. Click enable on the memory console to display the memory usage of the running program. As shown in the figure above:

Android studio memory features:

How to detect memory leaks

We click the dump Java heap button, and the app will freeze. In about a few tens of seconds,

After dump succeeds, the hprof file will be opened automatically.

If we want to know more about memory allocation, we can use allocation trader to see what memory is occupied. Click the start allocation tracking button. Start to allocate tracking. After some time, click stop allocation tracking to end tracking. When tracing is stopped, the. Alloc file opens automatically.

When you want to view the source code of a method, right-click the method and click jump to source.

Using leakcanary

Leakcanary is a simple and crude tool for detecting memory leaks launched by square.

Leakcanary will detect the memory recycling of the application. If it finds that garbage objects have not been recycled, it will analyze the current memory snapshot, that is, the. Hprof file used by the above mat, find the reference chain of the object and display it on the page. The advantage of this plug-in is that it can directly view the memory leak on the mobile phone and help us detect the memory leak.

use:

Add in the build.gradle file. Different compilers use different references:

Add leakcanary. Install (this) in the application oncreate method of the application, as follows:

After the application runs, leakcanary will automatically analyze the current memory status. If a leak is detected, it will be sent to the notification bar. Click the notification bar to jump to the specific Leak Analysis page.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>