skip to content

LeakCanary

LeakCanary watches destroyed Activities, Fragments and ViewModels, dumps the heap when one is retained and prints a leak trace. Paired with held Activity contexts, statics and stale listeners.

on this pageshow

explore

questions

7

How do you add LeakCanary 2 to an Android app, and why does it go in debugImplementation with no setup code?

level: juniorimportance: must knowfreq 62%

answer

  1. one Gradle line, debug only
  2. a manifest-merged ContentProvider
  3. installs before Application.onCreate()
  4. non-debuggable APK: it throws

basics

~10 s

Add com.squareup.leakcanary:leakcanary-android:2.14 as a debugImplementation dependency and write no code: a ContentProvider merged from the library installs it at startup, and keeping it debug-only matters because it refuses to run in a non-debuggable build.

solid answer

~40 s

LeakCanary 2 is one line: `debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14")`. The library's manifest contributes a non-exported `ContentProvider`; Android creates content providers after the `Application` instance exists but before `Application.onCreate()`, and that provider calls `AppWatcher.manualInstall(application)`, which registers the default watchers. So there is nothing to call. It is debug-only for two reasons: dumping the heap freezes the app and writes `.hprof` files to the device, which no user should see, and LeakCanary guards against mistakes by throwing an `Error` during initialization when the APK is not debuggable. A QA build that really needs it overrides the `leak_canary_allow_in_non_debuggable_build` boolean resource. You confirm it runs by filtering Logcat on the `LeakCanary` tag; it also adds a separate launcher icon for its leak list.

code

kotlin · 5 lines
kotlin
// app/build.gradle.kts
dependencies {
    // Debug builds only: LeakCanary installs itself, no code needed.
    debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14")
}

go deeper

for a junior

Recall the single debugImplementation line and that LeakCanary 2 needs no code. Be ready to say it is debug-only because heap dumps freeze the app.

for a middle

Explain the ContentProvider startup trick and the ordering: Application created, providers created, then Application.onCreate(). Mention how to confirm it in Logcat.

for a senior

Show you know the guard rails: the Error in non-debuggable builds, the override resource for QA builds, dumpHeap = false for demos, and keeping LeakCanary calls out of the main source set.

for a principal

Frame it as a team default: every debug build carries leak detection at no release cost, and any build that overrides the non-debuggable guard needs an explicit owner and reason.

## What LeakCanary is and what installing it means **LeakCanary** is an open-source memory-leak detector for Android apps. A **memory leak** here means the app keeps a reference to an object it no longer needs (most often a destroyed `Activity`), so the garbage collector cannot reclaim it. LeakCanary notices such objects while you use a debug build, captures a **heap dump** (a snapshot of every object in memory, saved as an `.hprof` file), analyzes it and tells you which chain of references keeps the object alive. Installing LeakCanary 2 is a single dependency in the app module: ```kotlin dependencies { debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14") } ``` That is the whole setup. The project documentation states it plainly: no code change is needed. ## How it starts without any code The trick is an Android startup ordering rule. When a process starts, Android creates the `Application` object, then creates the **content providers** declared in the merged manifest, and only then calls `Application.onCreate()`. 1. `leakcanary-android` pulls in `leakcanary-object-watcher-android`, whose manifest declares a non-exported `ContentProvider`. 2. Manifest merging copies that provider into your app's manifest. 3. When the provider is created, its `onCreate()` calls `AppWatcher.manualInstall(application)`. 4. `manualInstall()` loads the heap-dumping part of LeakCanary and installs the default watchers, which hook activity, fragment, `ViewModel`, service and root-view lifecycles. Because all of this happens before your own `Application.onCreate()`, the watchers are in place before any of your startup code runs. The automatic install can be switched off by overriding the `leak_canary_watcher_auto_install` boolean resource, after which you call `AppWatcher.manualInstall()` yourself. ## Why it belongs in debug builds only - **Heap dumps freeze the app.** Dumping the Java heap stops the process for a noticeable moment while LeakCanary shows a toast. - **Heap dumps are large and sensitive.** They contain everything in memory and are written to the device's storage; by default LeakCanary keeps the 7 most recent ones. - **Analysis costs memory and CPU.** It runs in the app process on a low-priority background thread. - **It adds UI.** LeakCanary adds a launcher icon for its leak list and posts notifications. - **Release builds carry no LeakCanary code.** With `debugImplementation`, nothing in the release variant references it. LeakCanary also defends itself against a misconfigured build: if the APK is not debuggable, initialization throws an `Error` titled "LeakCanary in non-debuggable build", so the mistake shows up as a crash at launch instead of shipping quietly. A non-debuggable QA build that genuinely needs leak detection sets the `leak_canary_allow_in_non_debuggable_build` boolean resource to `true`; the project recommends against including it in builds that real users get. ## Confirming it runs, and turning it down Filter Logcat on the `LeakCanary` tag after launching a debug build; it logs that it is installed and ready. If nothing appears, check the resolved dependencies of the debug variant. | Goal | How | |---|---| | Pause heap dumps at runtime, e.g. for a demo | `LeakCanary.config = LeakCanary.config.copy(dumpHeap = false)` | | Hide the extra launcher icon | Override the `leak_canary_add_launcher_icon` boolean resource, or call `LeakCanary.showLeakDisplayActivityLauncherIcon(false)` | | Run the analysis outside the app process | Depend on `leakcanary-android-process` instead of `leakcanary-android` | | Only one flavour gets it | Declare a `devDebugImplementation` configuration and add the dependency there | With `dumpHeap = false`, watching continues: retained objects are still counted, and LeakCanary looks for them again once dumping is switched back on. ## What changed from LeakCanary 1.x Older tutorials show `LeakCanary.install(this)` in `Application.onCreate()` plus a `releaseImplementation` of a `leakcanary-android-no-op` artifact. LeakCanary 2.0 removed both: installation became automatic, and the no-op artifact is gone because release code should not reference LeakCanary at all. Code that must use the watcher in release builds depends on `leakcanary-object-watcher-android`, which watches and counts retained objects but never dumps the heap. ## Common setup mistakes - Using `implementation` instead of `debugImplementation`, which puts LeakCanary into the release APK and makes it crash at startup. - Calling LeakCanary APIs from the `main` source set, which then fails to compile in release because the dependency is debug-only; such calls belong in a `src/debug` class. - Expecting leak reports during instrumentation tests: LeakCanary disables heap dumping when JUnit is on the classpath.

  • What happens if leakcanary-android is accidentally added with implementation and you build a release APK?
    The release APK is not debuggable, so LeakCanary's initialization throws an `Error` reporting "LeakCanary in non-debuggable build" and the app crashes at launch. That is deliberate: it turns a silent configuration mistake into an obvious one. The fix is `debugImplementation`; only a deliberate QA build should override `leak_canary_allow_in_non_debuggable_build`.
  • Why does LeakCanary use a ContentProvider rather than asking you to call an init method?
    Android creates declared content providers after the `Application` object but before `Application.onCreate()`, so a provider merged from a library's manifest runs automatically, early, with an application context. That removes the setup call that LeakCanary 1.x required, and it means nothing in your own source refers to LeakCanary, which is what lets the release build compile without it.

  • You must call LeakCanary.install(this) in Application.onCreate()
  • Add leakcanary-android-no-op as releaseImplementation to balance the debug dependency
  • LeakCanary is harmless in release builds, it just stays quiet there
  • LeakCanary needs a Gradle plugin to instrument activities
  • Hiding the launcher icon also stops heap dumps
open as a page

After rotating a screen several times, LeakCanary reports a leaked activity; how do you read its leak trace to find the reference to fix?

level: middleimportance: must knowfreq 55%

basics

~20 s

Read the leak trace from the GC root down to the destroyed activity. Objects are marked Leaking: NO, UNKNOWN or YES; the underlined suspects lie between the last NO and the first YES, and the one never cleared is the bug.

open as a page

What does LeakCanary 2 watch automatically, when does a watched object count as retained, and when does it dump the heap?

level: middleimportance: must knowfreq 50%

basics

~20 s

LeakCanary 2 watches destroyed activities, fragments, fragment views and services, cleared ViewModels and detached root views. One still reachable 5 seconds later, after a GC, is retained; it dumps the heap at 5 retained while visible, 1 in the background.

open as a page

How does LeakCanary tell a Library Leak from an Application Leak, and what do you do when a third-party SDK keeps leaking your activity?

level: seniorimportance: should knowfreq 30%

basics

~20 s

LeakCanary matches each trace against known leak patterns, AndroidReferenceMatchers by default; a leak whose only path runs through a matched reference is a Library Leak. For a leaking SDK, report it upstream and add your own matcher meanwhile.

open as a page

With LeakCanary, how do you make Android instrumentation tests fail on memory leaks, and why does the rule's position in a RuleChain matter?

level: seniorimportance: should knowfreq 32%

basics

~20 s

Add leakcanary-android-instrumentation as an androidTestImplementation dependency and use the DetectLeaksAfterTestSuccess rule or call LeakAssertions.assertNoLeaks(). Placed outside the activity rule it catches activity leaks; inside, it catches fragment leaks that vanish once the activity is destroyed.

open as a page

As Android lead, what LeakCanary policy should decide where leak detection runs, which leaks fail CI, and how known leaks are muted?

level: principalimportance: should knowfreq 20%

basics

~20 s

Run LeakCanary in debug builds for developers and in CI instrumentation tests, fail CI only on application leaks, mute known library leaks with matchers tied to an issue, and upload results grouped by leak signature.

open as a page

How do you make LeakCanary 2 watch an object it does not track automatically, such as a presenter released when its screen closes?

level: seniorimportance: nice to knowfreq 18%

basics

~10 s

Call AppWatcher.objectWatcher.expectWeaklyReachable(obj, description) at the moment the object should become garbage. It then follows the same 5-second retention check and heap-dump threshold as activities, and the description appears in the leak trace.

open as a page