Android Handler Memory Leaks
Article Summary
Dima Voronkevych from Bumble's Android team reveals how a simple postDelayed() call can silently keep 7 Activity instances alive in memory. Even with garbage collection, your app might be one rotation away from an OutOfMemoryError.
This deep dive from Bumble's engineering team dissects Android Handler memory leaks using real heap dumps and OQL analysis. The article walks through progressively better solutions, from static inner classes to a custom library that solves the problem elegantly.
Key Takeaways
- Anonymous Runnables create indirect this$0 references that prevent Activity garbage collection
- Static classes with WeakReferences work but create unreadable boilerplate code
- Handler.removeCallbacksAndMessages(null) in onDestroy clears all pending messages cleanly
- Bumble's WeakHandler library prevents leaks while keeping code readable and maintainable
Critical Insight
Three proven approaches fix Handler leaks: static classes with WeakReferences (verbose), manual cleanup in onDestroy (reliable), or Bumble's open source WeakHandler library (cleanest).