如何验证 LeakCanary 是否正常工作——我们在日志记录中看不到 LeakCanary

How to verify LeakCanary is working properly - We cannot see LeakCanary in logging

我有一个遗留项目

最近有神秘感OutOfMemoryException在制作中

我们使用以下内容来找出根本原因

debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'
implementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'

我们也在 ApplicationonCreate 中调用 refWatcher = LeakCanary.install(this);

但是,在完成上述所有操作并在模拟器中 运行 之后,我们使用

过滤掉我们的 Android Studio 日志

D/LeakCanary

但是,我们没有看到任何关于 LeakCanary 的日志。

有什么我们遗漏的吗?

但是,我们看到 0 个输出。

我们还有什么遗漏的吗?

您不需要添加

implementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'

泄漏金丝雀所需的唯一依赖项是:

debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.6.3'

之后,在您的 Application onCreate 方法中添加以下代码:

@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);

    // rest of your init code
}

之后会安装一个带有以下图标的应用程序:

现在您只需要 运行 您的应用程序。当发生内存泄漏时,将显示检测到泄漏的对话框。

当您打开带有上述图标的应用程序时,您将看到带有泄漏跟踪的内存泄漏:

LeakCanary 库现已升级到 2.x 版本。

要使用 LeakCanary,请将 leakcanary-android 依赖项添加到应用程序的 build.gradle 文件中:

dependencies {
  // debugImplementation because LeakCanary should only run in debug builds.
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.4'
}

就是这样,不需要更改代码!

通过过滤 Logcat 中的 LeakCanary 标签确认 LeakCanary 在启动时 运行:

D LeakCanary: LeakCanary is running and ready to detect leaks

来源:https://square.github.io/leakcanary/getting_started/