Leak Canary: How to detect leaks of Memory in our Android Application


Sometimes when we are developing Apps, we find errors like "java.lang.OutOfMemoryErros". Fortunately exist a great tools named Leak Canary to detect any leaks and suspects implementations. To use Leak Canary we must do the following steps:

1. To add the dependencies to our project through gradle:


dependencies {

  debugCompile 'com.squareup.leakcanary:leakcanary-android:1.3.1' // or 1.4-beta1
  releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1' // or 1.4-beta1
  testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.3.1' // or 1.4-beta1
}

2. To add the watcher into the Application App, something like:


// Variable watcher
private RefWatcher refWatcher;

// En el método onCreated agregar la instalación del LeakCanary
refWatcher = LeakCanary.install(this);

// Agregrar el método estático para obtener el watcher
public static RefWatcher getRefWatcher(Context context) {
        MyApplication application = (MyApplication) context.getApplicationContext();
        return application.refWatcher;
}

3. To use the watcher into suspect component, like:


RefWatcher refWatcher = MyApplication.getRefWatcher(context);
refWatcher.watch(/* Your component or variable to check here */);

Thanks for your comment