Android Detect memory leaks with the LeakCanary library


Example

LeakCanary is an Open Source Java library to detect memory leaks in your debug builds.

Just add the dependencies in the build.gradle:

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

Then in your Application class:

public class ExampleApplication extends Application {

  @Override public void onCreate() {
    super.onCreate();
    
    if (LeakCanary.isInAnalyzerProcess(this)) {
      // This process is dedicated to LeakCanary for heap analysis.
      // You should not init your app in this process.
      return;
    }

    LeakCanary.install(this);
  }
}

Now LeakCanary will automatically show a notification when an activity memory leak is detected in your debug build.

NOTE: Release code will contain no reference to LeakCanary other than the two empty classes that exist in the leakcanary-android-no-op dependency.