Android Profiler, LeakCanary & Memory Leak Diagnosis

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).

The #1 Cause of Memory Leaks: Activity Context Retention

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:

  • Static Fields: Storing an Activity context inside a companion object or static variable.
  • Unregistered Listeners: Registering an Activity with a system manager (e.g., LocationManager) without unregistering on destroy.
  • Unbounded Threads / Coroutines: Launching a Coroutine or Thread that holds an implicit reference to an Activity without cancelling it when the screen closes.

Automated Leak Detection with LeakCanary

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.

Using the Android Studio Memory & CPU Profiler

Open View > Tool Windows > Profiler to analyze real-time performance metrics:

  • Capture Heap Dump: Inspect all allocated Java/Kotlin objects, sorted by retained size.
  • Record Native Allocations: Detect C/C++ memory leaks in Vulkan, OpenGL, or native audio libraries.
  • CPU Trace (System Trace): Identify which Composable functions cause frame drops during scrolling.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is an ANR (Application Not Responding) and how do I profile it?

An ANR dialog appears when the main thread is blocked for 5+ seconds on user input, or 10+ seconds in a BroadcastReceiver. In the Android Studio CPU Profiler, record a System Trace to locate the exact method running on the main thread causing the freeze.

Q2. Should LeakCanary ever be included in release builds?

NO! Always use `debugImplementation`. LeakCanary freezes the app while creating heap dumps, consumes high disk storage, and is intended strictly for developer debugging.

Q3. How does WeakReference help prevent memory leaks?

A `WeakReference` allows an object to be referenced without preventing the Garbage Collector from finalizing and reclaiming it when memory is needed.

Explore Related Android Development Classes & Next Steps

Broaden your foundational and advanced Android application development skills across our curriculum:

Activity Lifecycle & Memory

Identify leaked Activity contexts held by static singletons or listeners.

ViewModel State Management

Avoid passing Context or View references into ViewModel classes.

Bitmap Optimization & Caching

Prevent OutOfMemoryError (OOM) by downsampling large camera bitmaps.

Debugging & Troubleshooting Errors

Diagnose ANR (Application Not Responding) and crash stack traces.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!