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

FiX*_*XiT 4 android memory-leaks leakcanary

我正在使用泄漏金丝雀来检测我的 Android 应用程序中的潜在泄漏。但是当我开发 feature 时,它​​开始不时地进行堆转储非常令人不安。我在debugImplemation 中使用它。

dependencies {
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.4'
} 
Run Code Online (Sandbox Code Playgroud)

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

    LeakCanary.Config config = LeakCanary.getConfig().newBuilder()
                        .dumpHeap(false)
                        .build();
                LeakCanary.setConfig(config)
Run Code Online (Sandbox Code Playgroud)

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

sco*_*out 9

  • 步骤 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)
            }

Run Code Online (Sandbox Code Playgroud)
  • 第 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
    }

Run Code Online (Sandbox Code Playgroud)
  • 第 4 步 - 在 Application 类中 onCreate()

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

Run Code Online (Sandbox Code Playgroud)

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