Memory Leaks
Mayokun Yusuf. June 05, 2025
Memory Leaks in Android: Detection and Prevention
Introduction
What are Memory Leaks?
Understanding Memory Leaks
A recent study found memory leaks in 39% of the
top 100 Android apps on Google Play.
Common Causes:
Static fields – 28%
Unclosed resources – 24%
Inner classes – 18%
Other causes – 30%
For example, Pokemon Go suffered from memory leaks, leading to a 12% increase in crash rates and 23% more users reporting performance issues.
Garbage Collection (GC)
GC is the automatic process used by Android to reclaim memory that is no longer in use, so that your app doesn’t run out of memory and crash.
What GC Does
How GC Works in Android (Dalvik & ART)
Android apps run on the ART (Android Runtime) or older Dalvik VM, both of which use automatic garbage collection. Here's how it generally works
Causes of Memory Leaks
1. Static references to Context (Activity/Fragment)
Why is this a memory leak?
2. Handlers and Runnables: Delayed messages or runnables may keep the Activity in memory even after it’s destroyed.
Causes of Memory Leaks
3. Views not released (e.g., Bitmaps): ImageViews holding large bitmaps can leak if not explicitly released.
4. Singletons holding Context Avoid using Activity context in singletons. Use ApplicationContext instead.
5. Leaking Fragments / Activities FragmentManager leaks due to retained fragments or mismanagement.
Causes of Memory Leaks
6. WebView leaks Improper WebView lifecycle management can cause memory leaks.
7. Listeners and Observers Forgetting to unregister listeners, broadcast receivers, or LiveData observers
8. Inner classes / anonymous classes. Non-static inner classes hold implicit references to outer classes.
Preventing Memory Leaks
Detecting Memory Leaks
Detecting Memory Leaks
Add the dependency to your build.gradle (app-level):
Build and run the app
LeakCanary auto-hooks into the Application class.
When an Activity/Fragment is destroyed but not GC’d, it logs and shows a leak notification
View Leak Report
Detecting Memory Leaks
Open Android Studio.
Run your app on an emulator or physical device.
Click View > Tool Windows > Profiler.
THANK YOU.