使用 LeakCanary 库检测内存泄漏
LeakCanary 是一个开源 Java 库,用于检测调试版本中的内存泄漏。
只需在 build.gradle 中添加依赖项:
 dependencies {
   debugCompile 'com.squareup.leakcanary:leakcanary-android:1.5.1'
   releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
   testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.5.1'
 }
然后在你的 Application 类:
public class ExampleApplication extends Application {
  @Override public void onCreate() {
    super.onCreate();
    
    if (LeakCanary.isInAnalyzerProcess(this)) {
      // This process is dedicated to LeakCanary for heap analysis.
      // You should not init your app in this process.
      return;
    }
    LeakCanary.install(this);
  }
}
现在,当你的调试版本中检测到活动内存泄漏时,LeakCanary 会自动显示通知。
注意:除了 leakcanary-android-no-op 依赖项中存在的两个空类之外,发行代码不包含对 LeakCanary 的引用。