LeakCanary, a memory leak detection tool

Source: Internet
Author: User

LeakCanary, a memory leak detection tool

Simple: we do not create a service, not to make money; we make money to provide better services. We think this is the attitude towards doing things.

Everyone who learns to use Java should know that the garbage collection mechanism provided by Java JVM is extremely useful. However, we also know that the garbage collection mechanism is not omnipotent, and improper use may easily cause memory leakage. We have also introduced the commonly used Memory leak detection Tool MAT in Java. Currently, the most commonly used Memory analysis Tool for Java programs is MAT (Memory Analyzer Tool), which is an Eclipse plug-in, there are also separate RCP clients.

If you are not familiar with MAT, or do not know about Java garbage collection, you can
View my article: http://blog.csdn.net/yzzst/article/details/26621861

Today, we will not talk about MAT here. We will talk about LeakCanary, a more useful open-source tool.

LeakCanary is essentially an open-source tool that automatically detects Memory leakage of Android applications based on MAT, by integrating the tool code into your Android project, you can use a beautiful interface during program debugging and development.

You can detect and locate memory leaks at any time, without having to assign a dedicated person to detect memory leaks during the development process. This greatly facilitates the development of Android applications.

In general, LeakCanary has the following obvious advantages:

Github address: https://github.com/square/leakcanary

How to use it? Apply the official translation documents:

LeakCanary


Android and Java Memory leakage detection.

"A small leak will sink a great ship."-Benjamin Franklin

The treasure of a thousand miles is destroyed by the ant nest. -Han Feizi Yu Lao

Start to use

Add references to build. gradle. Different references are used for different compilation:

 dependencies {   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3'   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3' }

In Application:

public class ExampleApplication extends Application {  @Override public void onCreate() {    super.onCreate();    LeakCanary.install(this);}

In this way, everything is ready! In debug build, LeakCanary automatically displays a notification if the memory leakage of an activity is detected.

How to Use

Use RefWatcher to monitor objects that are supposed to be recycled.

RefWatcher refWatcher = {...}; // monitor refWatcher. watch (schrodingerCat );

LeakCanary. install () returns a pre-defined RefWatcher and enables ActivityRefWatcher to automatically monitor the Activity leaked after activity. onDestroy () is called.

public class ExampleApplication extends Application {  public static RefWatcher getRefWatcher(Context context) {    ExampleApplication application = (ExampleApplication) context.getApplicationContext();    return application.refWatcher;  }  private RefWatcher refWatcher;  @Override public void onCreate() {    super.onCreate();    refWatcher = LeakCanary.install(this);  }}

Use RefWatcher to monitor Fragment:

public abstract class BaseFragment extends Fragment {  @Override   public void onDestroy() {    super.onDestroy();    RefWatcher refWatcher = ExampleApplication.getRefWatcher(getActivity());    refWatcher.watch(this);  }}
How does one copy the leak trace?

In Logcat, you can see a leak trace similar to this:

In com.example.leakcanary:1.0:1 com.example.leakcanary.MainActivity has leaked:* GC ROOT thread java.lang.Thread.<Java Local> (named 'AsyncTask #1')* references com.example.leakcanary.MainActivity$3.this$0 (anonymous class extends android.os.AsyncTask)* leaks com.example.leakcanary.MainActivity instance* Reference Key: e71f3bf5-d786-4145-8539-584afaecad1d* Device: Genymotion generic Google Nexus 6 - 5.1.0 - API 22 - 1440x2560 vbox86p* Android Version: 5.1 API: 22* Durations: watch=5086ms, gc=110ms, heap dump=435ms, analysis=2086ms

You can even share these items through the share button.

Memory leakage caused by SDK

Over time, many memory leaks in the SDK and vendor ROM have been fixed as soon as possible. However, when such a problem occurs, General developers can do very little.

LeakCanary has a list of ignored known issues, AndroidExcludedRefs. java. If you find a new problem, please submit an issue and attach the leak trace, reference key, machine model, and SDK version. If the link to the dump file can be attached, it would be better.

This is especially important for the latest Android release. You have the opportunity to help detect new memory leaks in the early stages, which is of great benefit to the entire Android community.

The development version of the Snapshots package is here: https://oss.sonatype.org/content/repositories/snapshots/

Out of leak trace

Sometimes, leak trace is not enough. You need to dig the dump file through MAT or YourKit.

You can find the problem by using the following methods:

Custom

UI Style

DisplayLeakActivity has a default icon and tag. You only need to replace the following resources in your own APP resources.

res/  drawable-hdpi/    __leak_canary_icon.png  drawable-mdpi/    __leak_canary_icon.png  drawable-xhdpi/    __leak_canary_icon.png  drawable-xxhdpi/    __leak_canary_icon.png  drawable-xxxhdpi/    __leak_canary_icon.png<?xml version="1.0" encoding="utf-8"?><resources>  <string name="__leak_canary_display_activity_label">MyLeaks</string></resources>
Save the leak trace
DisplayLeakActivity saves up to 7 heap dumps & leak traces in the app directory. You can change that number by providing R.integer.__leak_canary_max_stored_leaks in your app:

In the APP directory, DisplayLeakActivity saves seven dump files and leak trace. You can define R. integer. _ leak_canary_max_stored_leaks in your APP to overwrite the default value of the class library.

<?xml version="1.0" encoding="utf-8"?><resources>  <integer name="__leak_canary_max_stored_leaks">20</integer></resources>
Upload leak trace to server

You can change the default action after processing, and upload the leak trace and heap dump to your server for statistical analysis.

To create a LeakUploadService, the simplest thing is to inherit DisplayLeakService:

public class LeakUploadService extends DisplayLeakService {  @Override  protected void afterDefaultHandling(HeapDump heapDump, AnalysisResult result, String leakInfo) {    if (!result.leakFound || result.excludedLeak) {      return;    }    myServer.uploadLeakBlocking(heapDump.heapDumpFile, leakInfo);  }}

Make sure that the release version uses RefWatcher. DISABLED:

public class ExampleApplication extends Application {  public static RefWatcher getRefWatcher(Context context) {    ExampleApplication application = (ExampleApplication) context.getApplicationContext();    return application.refWatcher;  }  private RefWatcher refWatcher;  @Override public void onCreate() {    super.onCreate();    refWatcher = installLeakCanary();  }  protected RefWatcher installLeakCanary() {    return RefWatcher.DISABLED;  }}

Custom RefWatcher:

public class DebugExampleApplication extends ExampleApplication {  protected RefWatcher installLeakCanary() {    return LeakCanary.install(app, LeakUploadService.class);  }}

Do not forget to Register service:

<?xml version="1.0" encoding="utf-8"?><manifest         xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    >     <application android:name="com.example.DebugExampleApplication">           <service android:name="com.example.LeakUploadService" />     </application></manifest>
Demo

A very simple LeakCanary demo: https://github.com/liaohuqiu/leakcanary-demo

/*
* @ Author zhoushengtao (Zhou Shengtao)
* @ Since 15:11:00, January 1, September 13, 2015
* @ Weixin stchou_zst
* @ Blog http://blog.csdn.net/yzzst
* @ Exchange and learning QQ group: 341989536
* @ Private QQ: 445914891
/

Copyright Disclaimer: Reprint Please note: http://blog.csdn.net/yzzst. This article is the original article of the blogger and cannot be reproduced without the consent of the blogger.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.