android - 从调试应用程序中暂时禁用泄漏金丝雀

标签 android memory-leaks leakcanary

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

dependencies {
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.4'
} 
现在,我想暂时禁用它。我怎样才能做到这一点 ?。我发现的一个答案是
    LeakCanary.Config config = LeakCanary.getConfig().newBuilder()
                        .dumpHeap(false)
                        .build();
                LeakCanary.setConfig(config)
它可以工作,但在 Release模式下,此库不可用,因此无法编译。如果我使用 实现 而不是 调试实现 , 我会增加 apk 大小而不增加任何值(value)。有什么我可以做的吗?

最佳答案

  • 第 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 步 - 在应用程序类中 onCreate()
  • 
         if (BuildConfig.DEBUG) {
           configureLeakCanary();
         }
    
    
    引用 - https://square.github.io/leakcanary/recipes/#disabling-leakcanary

    关于android - 从调试应用程序中暂时禁用泄漏金丝雀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62570358/

    相关文章:

    java - 如何获取SVN修订号然后传递给android

    java - 使用 TensorFlow for Java 的内存泄漏

    android - 即使在 onDestroy() 方法中将实例设置为 null,Activity 仍然会泄漏

    android - 使用动态屏幕时如何防止内存泄漏?

    java - 更换 fragment 时内存泄漏

    android - 从外部存储 SD 卡打开数据库

    android - 如何将 android 开源项目克隆到我的桌面

    java - 如何在每次方法执行时创建(和写入)新的日志文件?

    c - 检测到 glibc - 双重释放或损坏

    android - 如何在 android 下获得工作的动态 ToggleButton 文本?