Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable Leak Canary temporarily from Debug apps

I am using leak canary to detect potential leaks in my Android application. But when I was developing feature , it is quite disturbing as it starts taking heap dumps time to time. I am using it in debugImplemetation.

dependencies {
  debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.4'
} 

Now , I want to disable it temporarily. How can I do that ?. One anwer I found is

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

It works but In release mode this library is not available so it will not compile. If I use implementation instead of debugImplemetation , I will increase apk size and not adding any value. Is there anything I can do ?

like image 388
FiXiT Avatar asked Dec 18 '22 13:12

FiXiT


1 Answers

  • Step 1 - Continued to keep the Leak canary dependency as debugImplementation
  • Step 2 - Create a Util method in the src/debug/java/
   

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

  • Step 3 - Create the same Util function in the src/release/java to suppress compiler errors

    /**
     * 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
    }

  • Step 4 - In the Application class onCreate()

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

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

like image 104
scout Avatar answered Dec 21 '22 09:12

scout