Search code examples
androidmemory-leaksleakcanary

LeakCanary 2: Does one manually have to watch objects?


I just added Leak Canary 2 to my app build.gradle as described in the official docs:

dependencies {
  // debugImplementation because LeakCanary should only run in debug builds.
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.2'
}

Now, when I run my app and check the logcat, I can find

2020-03-22 18:20:31.858 2401-2401/? D/LeakCanary: Installing AppWatcher

so the installation worked.

But is that everything I need? Or do I in addition have to watch objects manually using AppWatcher.objectWatcher.watch? That's not clear to me. Currently no issues are report by LeakCanary to me, but I doubt I did everything that perfect.


Solution

  • Yes and no.

    Yes, it will automatically detect leaked Activity, Fragment, Fragment view (the View returned from the Fragment's onCreateView method), and ViewModel instances (per the docs for Config and the source for AndroidXFragmentDestroyWatcher), with no need to manually watch these objects.

    No, it will not automatically detect leaked instances of any other objects. For those, you'll need to manually watch them. For instance, this recipe from the documentation describes how you'd make LeakCanary watch for leaked Service instances.

    Also note that if the app is visible, it won't trigger a heap dump until it detects 5 retained objects. Putting the app in the background will trigger a dump to happen immediately, though it will display a notification in the meantime (docs).