purpose

This article is intended to implement “Library is only used in the Debug package, Release package automatically removed” function!

background

Here’s an example:

LeakCanary is a convenient Library to detect memory leaks, but we can only use it in the Debug package and need to remove it once it goes live, so we need to remove it in the Release package.

Without some means, we can only remove it by manual comment when we go online, but this has two disadvantages: first, it is easy to forget, and second, if there are too many libraries to remove, it is quite troublesome!

So, here’s how to implement the Release package to automatically remove unnecessary libraries!

Specific operation

Step 1: Add the following code to the build.gradle file of the main Module. The path can be adjusted according to your own needs. Here uses SRC /debug/ Java as an example:

android{
    sourceSets {
        debug {
            java.srcDirs = ['src/debug/java']
        }
        release {
            java.srcDirs = ['src/release/java']
        }
    }
}
Copy the code

Step 2: Create a folder according to the path in Step 1 by referring to the following directory structure:

Main Module | - SRC | - debug Java | -- - | -- - | package name -- MMHConfig. Java / / implementation method and the function of the debug packages need | - the main Java | -- - | -- - | package name - release | - Java | | - package name -- MMHConfig. Java / / implementation methods, only not implement functionCopy the code

Demo

The contents of the mmhconfig. Java file in the debug folder:

public class MMHConfig { public static void setting(Application application) { initLeakCanary(); } / initialization LeakCanary * * * * / private void initLeakCanary () {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); }}Copy the code

The contents of mmhconfig. Java in the release folder:

public class MMHConfig {

    public static void setting(Application application) {

    }

}
Copy the code