Android Memory Leak Checks Beyond LeakCanary: Teardown, Cache Files and Test State
LeakCanary finds destroyed Activities that stay reachable. These four cases were not heap leaks: startup work that survived teardown, two cache files left on disk, and an exception that surfaced in a later test.

One test out of 1,338 failed. It failed twice in a row, with an UncaughtExceptionsBeforeTest error and an NPE involving ContextImpl.sSharedPrefsCache. RecallPing's failing test exposed startup work that outlived Robolectric teardown and reached Android state that had already been reset.
A memory leak occurs when references keep objects reachable beyond their useful lifetime, preventing garbage collection. The famous Android cases are an Activity held by a static field or an inner-class Handler. The four cases below, from my shipped Kotlin and Compose apps, show startup work that survived teardown, two cache files left on disk, and an exception that surfaced in a later test.
What LeakCanary and Android Studio's Memory Profiler detect
LeakCanary hooks the Android lifecycle and, by default, watches destroyed Activity and Fragment instances, destroyed fragment Views and cleared ViewModels. After waiting five seconds and running garbage collection, LeakCanary treats a watched object as retained if its weak reference still points to it. Automatic heap dumps wait for a retained-object threshold, and you can tell it to watch other objects you expect to be collected. Its leak trace shows a strong-reference path from a GC root to the retained object. Start with the references LeakCanary underlines, then check which owner should have released its reference.
Android Studio's heap dump view has a filter that shows Activity and Fragment instances it suspects are leaking. That is one view of the dump, not the whole of it.
A heap dump can show what retains a Java object. To find out whether a coroutine finished, a cache file was deleted, or an exception escaped a test, inspect the relevant teardown or cleanup path.
Coroutine scope leak: the Application scope nobody owned
RecallPingApplication.onCreate started its startup work, the default rule seeder and the reclassify enqueue, with launch in scopes that nothing owned. Two singleton scopes, one for @ApplicationScope and one for the listener-health coordinators, were never cancelled either. Kotlin's docs say new coroutines can only be launched in a scope that defines and manages their lifecycle. Here the lifecycle was "until the process dies", and Robolectric tears down the test application while the JVM can keep running.
The first fix was the obvious one: put the startup work in an owned startupScope, and cancel it and both singleton scopes in onTerminate(). Code review failed it. Kotlin's docs state that coroutine cancellation is cooperative. A coroutine can stop at an explicit cancellation check, but a plain blocking SharedPreferences call can keep running after cancel(). A child blocked in that read survived, and my own test had only asserted that the scope was no longer isActive. That is the part I got wrong: I proved the flag flipped, not that the work had stopped.
The correction started with a RED test that parks a child on a CountDownLatch and asserts onTerminate() does not return until the child is released. Then the fix:
override fun onTerminate() {
// Cancel every scope before joining any, so a child blocked on another scope's work is released.
val jobs = listOf(startupScope, applicationScope, coordinatorScope).map { scope ->
checkNotNull(scope.coroutineContext[Job]) { "scope has no Job to join" }.also { it.cancel() }
}
runBlocking { withTimeout(TERMINATE_JOIN_TIMEOUT_MS) { jobs.joinAll() } }
super.onTerminate()
}
Cancel and then join: isActive == false is not the same as "the work is finished", and the join is bounded by a timeout that throws instead of giving up quietly.
A second test checks that none of the three scopes is configured to dispatch on Main, because runBlocking on the main thread can deadlock if finishing the work needs that same thread. Android does not call Application.onTerminate() on production devices, so the failure and the teardown fix were verified in Robolectric. After the correction the full suite, now 1,340 tests with the two new ones, passed with no failures, twice, the second time with --rerun-tasks, plus ktlint and detekt.
Temp files are a resource leak, too
Two apps leaked files, not objects. A leftover file occupies disk space after the app has finished with it, and neither fix came from a profiler.
LeadPing and a staged PDF. When you attach a PDF, the app copies it into a temp file and holds its path in the pending attachment. Ownership only moves to the attachment store at send time. Code review found three exits that left the file behind: picking a second PDF, tapping the remove button, and the ViewModel being cleared with one still staged. The fix is one helper called from all three:
private fun deleteStagedPdfTemp(pa: PendingAttachment?) {
if (pa?.kind != AttachmentKind.Pdf) return
val path = pa.pdfSourcePath ?: return
try { File(path).delete() } catch (e: Exception) { /* best-effort cache cleanup */ }
}
The ViewModel now attempts the delete when a new attachment is read successfully, before replacing the staged one, on explicit removal and when it is cleared. The helper ignores a false return and catches deletion exceptions.
The regression test creates two real temp files, stages the first, re-picks the second and asserts the first is gone, then removes the second and asserts that one is gone too. It documents the deliberate revert that must make it fail: drop the delete calls and both files survive. The onCleared path got the same call, but the test as committed covers re-pick and remove only.
ChatPing and the camera JPEG. The camera flow writes into a cache file exposed through a FileProvider. Only the cancel path deleted it, so every successful photo left a JPEG in cacheDir for the system to clear later. The fix attempts to delete it after the bytes have been read and reported, and the order matters: delete first and the reader gets a URI whose file no longer exists. A second leak was in the same flow. Launching the camera with no handler could throw before the result callback ran, bypassing cleanup. That path now attempts to delete the staged file, and the failure goes through the same failed-read result a corrupt capture produces. The commit adds tests for the pending-capture state and for the read-then-cleanup ordering.
Test state that leaks into the next test
Here I blamed the wrong class first. In PlannedPing, a run that included MainViewModelTest and ScreenTopBannerTest logged two failures out of 42 tests, both UncaughtExceptionsBeforeTest. Each class passed alone, so my backlog note blamed MainViewModelTest.
I re-read the recorded failure instead of the note. The suppressed exception was IllegalStateException: Illegal connection pointer inside Room's invalidation tracker on Dispatchers.Default, with no com.plannedping frame in it. MainViewModelTest is neither Robolectric nor Room-backed, and the report timestamps showed the two classes ran at the same time in separate forked JVMs, so neither could poison the other. The source was ScreenTopBannerTest itself. Its default config booted the real Hilt Application, whose Room-backed application-scoped collectors raced the suite's per-test SQLite teardown, and the next runTest in that fork reported the escaped exception.
Two fixes followed. The banner test now runs on a bare android.app.Application, which it can because it renders fakes. And MainViewModelTest got an @After that calls viewModelScope.cancel() on every ViewModel it built, because no ViewModelStore ever clears them. Android's docs say viewModelScope is cancelled when the ViewModel is cleared. This test constructs its ViewModels directly, so its @After cancels their scopes. A later commit made the bare Application the default for the whole suite, with application=android.app.Application in robolectric.properties.
The backlog heading marks the issue resolved. The fix entry still calls for a combined rerun of MainViewModelTest and the ad tests.
When WhileSubscribed would break a synchronous read
One earlier PlannedPing commit batched 22 bugs, five of them under memory and leaks. Its message says one ViewModel cache switched to SharingStarted.WhileSubscribed. The implementation kept Eagerly, and the commit adds a comment explaining why: the delete dialog reads StateFlow.value synchronously, before a subscriber may have started upstream collection, so a lazily started cache would hand it the initial empty value. Before you switch a cache to WhileSubscribed to stop it holding data, check who reads .value without collecting.
Checklist for the next Android memory leak
- Who owns this scope? Every
launchneeds a scope with a named owner and a place where it is cancelled. If the answer is "the process", say so on purpose. - Does cancel end the work? Cancellation is cooperative, so check what a blocked child does, and join when the next thing depends on it.
- What deletes this file on every exit? List the exits: success, cancel, replace, remove, no handler available, ViewModel cleared. Test the exits, not just the happy path.
- Does a test clear what it creates? Cancel the
viewModelScopeyou built, and do not boot the realApplicationwhen fakes are enough. - Is the failure reported where it happened? An uncaught exception from earlier coroutine work can surface at the start of a later
runTest. Read the stack before trusting the test name. - Which tool covers it? LeakCanary and the heap dump cover objects that stay reachable. Deletion and teardown need their own tests or a review rule.
Stability work like this is also the first thing I look at in a rescue, which is what App Rescue is for. A leak that never crashes is the kind a crash-free rate cannot see, and a leaked test looks like a flaky one until you sort the bad runs by what produced them.
Keep reading
- One Test Automation Framework for Mobile? I Run Three, One per LayerI counted the flow files, XCUITest files and androidTest files across my own Android and iOS apps, then read the git history for what each layer was actually good for.
- My Notes Said Firebase Test Lab Ran on Every Gate. It Never Went Green.I set up a Firebase Test Lab device matrix for an Android app in one evening. Months later my notes said it ran on every gate. The run history said something else.
- Claude Code in Android Studio: The Editor Is the Easy PartThe plugin gives the agent diffs, your selection and lint. The phone is reached from the terminal, and that is where my agents' habits, my screenshots and my own guard hook surprised me.