LeakCanary
A memory leak detection library for Android.
Quick Demo
Add implementation 'com.squareup.leakcanary:leakcanary-android:2.x' to your app's build.gradle file.class MyApp : Application() {
override fun onCreate() {
super.onCreate()
LeakCanary.install(this)
}
}Launch the app and watch for LeakCanary notifications when memory leaks are detected.
Quick Start
com.squareup.leakcanary:leakcanary-androidSetup Steps
- Add the LeakCanary dependency to your build.gradle file.
- Initialize LeakCanary in your Application class.
- Run your app and monitor for leak notifications.
Overview
LeakCanary is a memory leak detection library for Android that automatically identifies and reports memory leaks by dumping and analyzing the heap, helping developers improve app performance and stability.
Features
Use Cases
When Not to Use
Usage Examples
LeakCanary.config = LeakCanary.config.copy(dumpHeap = true)Enable heap dumping in LeakCanary configuration.
class MyApp : Application() {
override fun onCreate() {
super.onCreate()
LeakCanary.install(this)
}
}Initialize LeakCanary in a custom Application class.
Common Pitfalls
- Can increase app size and startup time
- May produce false positives without proper configuration
- Requires careful handling in multi-module projects
Integration
Works well with
- Test in various scenarios to avoid false positives
- Consider using only in debug builds to minimize impact
Alternatives
Android Profiler
Built-in tool in Android Studio for real-time memory monitoring and analysis.
MAT (Memory Analyzer Tool)
Standalone Java heap analyzer for deep memory leak investigation.
FAQ
What is LeakCanary?
LeakCanary is an open-source library that automatically detects memory leaks in Android applications by analyzing heap dumps.
How does LeakCanary work?
It hooks into the Android lifecycle, dumps the heap when a leak is suspected, and provides a detailed report with leak traces.
Is LeakCanary suitable for production use?
It can be used in production, but it is often recommended for debug builds due to performance overhead and resource usage.
How do I disable LeakCanary in release builds?
Use build flavors or conditional initialization in your Application class to exclude it in release variants.
Does LeakCanary support Kotlin?
Yes, it is written in Kotlin and fully compatible with both Kotlin and Java projects.
Can I customize LeakCanary's behavior?
Yes, through configuration options in LeakCanary.config, such as enabling/disabling heap dumping or setting up custom leak detectors.