A Memory Leak in Android occurs when an application retains an unneeded reference to an object (such as a destroyed Activity) in memory, preventing the Garbage Collector (GC) from reclaiming its allocated space. Over time, memory consumption accumulates until the app inevitably crashes with an OutOfMemoryError (OOM).
Because an Activity contains a reference to the entire View hierarchy, custom drawables, and window managers, leaking a single Activity typically leaks 5 MB to 30 MB of RAM. Common leak patterns include:
LocationManager) without unregistering on destroy.LeakCanary is the premier open-source memory leak detection library developed by Square. It requires zero lines of code in your application classes:
// In app/build.gradle.kts:
dependencies {
// debugImplementation ensures LeakCanary is NEVER bundled in production release builds!
debugImplementation("com.squareup.leakcanary:leakcanary-android:2.14")
}
When running your debug build, LeakCanary automatically tracks destroyed Activities and Fragments. If an instance is still in memory 5 seconds after onDestroy(), LeakCanary dumps the Java heap, traces the shortest path of strong references from GC roots, and displays an interactive notification showing the exact line of code causing the leak.
Open View > Tool Windows > Profiler to analyze real-time performance metrics:
Broaden your foundational and advanced Android application development skills across our curriculum:
Identify leaked Activity contexts held by static singletons or listeners.
Avoid passing Context or View references into ViewModel classes.
Prevent OutOfMemoryError (OOM) by downsampling large camera bitmaps.
Diagnose ANR (Application Not Responding) and crash stack traces.