Detecting memory leaks with LeakCanary
LeakCanary is an open-source library developed by Square that helps us detect memory leaks in our apps. The library has knowledge of the internals of the Android Framework that allows it to narrow down the cause of the memory leak. It helps reduce the Application Not Responding (ANR) errors and out-of-memory crashes in our apps. Here are some of the most common causes of memory leaks:
- Storing instances of
Activity
asContext
filed in an object that survives activity recreation due to configuration changes - Forgetting to unregister broadcast receivers, listeners, callbacks, or RxJava subscriptions when they are no longer needed
- Storing references to
Context
in a background thread
LeakCanary is quite easy to set up and no code implementation is needed to use it. We just need to add the leakcanary-android
dependency in our libs.version.toml
file:
leakcanary-android = "com.squareup.leakcanary:leakcanary-android:2.12"...