LeakCanary is the gold standard for automatic memory leak detection in Android debug builds. It instruments Activities, Fragments, ViewModels, and other objects automatically — without any code changes — and produces a clear leak trace showing the exact reference chain from a GC root to the leaked object.Documentation Index
Fetch the complete documentation index at: https://mintlify.com/AmolPardeshi99/android-performance-skills/llms.txt
Use this file to discover all available pages before exploring further.
Setup
Add LeakCanary as adebugImplementation dependency so it is never included in release builds:
No code initialization is required. LeakCanary installs itself automatically via a
ContentProvider declared in its manifest — no Application.onCreate() call needed.Watching custom objects
LeakCanary automatically watches Activities, Fragments, ViewModels, and View instances. For any other object that should become garbage after a well-defined point, register it explicitly:onDestroyView, after a screen is dismissed, or after a session ends. If the object has not been GC’d within five seconds, LeakCanary captures a heap dump and computes the leak trace.
CI gate with DetectLeaksAfterTestSuccess
Running LeakCanary
Add the dependency
Add
debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14") to your app module’s build.gradle.kts and sync Gradle.Run the app in debug mode
Launch a debug build on a device or emulator. LeakCanary installs itself automatically — no setup code required.
Navigate between screens
Open and close Activities, Fragments, and dialogs repeatedly. LeakCanary watches each object as it goes through its destruction lifecycle.
Reading the leak trace
A LeakCanary leak trace reads from top to bottom: the GC root at the top is the reason the object cannot be collected (e.g., a static field or a running thread), followed by each reference in the chain, and finally the leaked object at the bottom. Example structure:- The first node marked Leaking: YES is where the problem originates.
- The reference label on the arrow (e.g.,
mContext) tells you exactly which field holds the reference. - Work upward from the leaked object to find the retaining root — that is the code to fix.
Hilt / DI scope alignment
Mismatched DI scopes are a common source of leaks that LeakCanary will surface. A@Singleton that holds an @ActivityScoped dependency keeps the Activity alive for the entire process lifetime.