Interview frequency: …
Short answer
It happens when a long-lived object holds a strong reference to an object whose lifecycle has ended (such as an Activity), preventing the garbage collector (GC) from freeing it; LeakCanary detects it by tracking objects through weak references.
Explanation
LeakCanary watches Activity and Fragment objects after onDestroy is called. It waits 5 seconds and then runs garbage collection; if the object remains in memory, it takes a heap dump through Hprof and analyzes the reference tree (retention path) to show the developer the exact line that prevented the object from being released.
Code example
// Add LeakCanary as a debug-only dependency in build.gradle:
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.14'
// Classic leak example:
object SingletonManager {
// Fatal mistake: retaining an Activity Context in a static object!
var leakedActivity: Activity? = null
}Common mistakes
- Registering listeners and callbacks in singleton objects without unsubscribing when the screen closes.
- Storing View references in CoroutineScope objects or long-running worker threads.