从调试应用程序中暂时禁用 Leak Canary

Disable Leak Canary temporarily from Debug apps

我正在使用 leak canary 来检测我的 Android 应用程序中的潜在泄漏。但是当我开发功能时,它开始时不时地进行堆转储,这非常令人不安。我在 debugImplemetation.

中使用它
dependencies {
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.4'
} 

现在,我想暂时禁用它。我怎样才能做到这一点 ?。我找到的一个答案是

    LeakCanary.Config config = LeakCanary.getConfig().newBuilder()
                        .dumpHeap(false)
                        .build();
                LeakCanary.setConfig(config)

它可以工作,但在发布模式下,该库不可用,因此无法编译。如果我使用 implementation 而不是 debugImplemetation ,我将增加 apk 大小而不添加任何值。有什么我可以做的吗?

  • 第 1 步 - 继续将 Leak Canary 依赖项保留为 debugImplementation
  • 第 2 步 - 在 src/debug/java/
  • 中创建 Util 方法
   

     import leakcanary.AppWatcher
        import leakcanary.LeakCanary
            fun configureLeakCanary(isEnable: Boolean = false) {
                LeakCanary.config = LeakCanary.config.copy(dumpHeap = isEnable)
                LeakCanary.showLeakDisplayActivityLauncherIcon(isEnable)
            }

  • 第 3 步 - 在 src/release/java 中创建相同的 Util 函数以抑制编译器错误

    /**
     * This method is added just to ensure we can build the demo application in release mode.
     */
    fun configureLeakCanary(isEnable: Boolean = false) {
        // This log is added just to supress kotlin unused variable lint warning and this will never be logger.
        android.util.Log.i("Demo Application", "Leak canary is disabled - State isEnable - ${isEnable}")
        // do nothing
    }

  • 第 4 步 - 在应用程序中 class onCreate()

     if (BuildConfig.DEBUG) {
       configureLeakCanary();
     }

参考 - https://square.github.io/leakcanary/recipes/#disabling-leakcanary