Include library based on product flavor

Ex) I want to use debugging tool libraries such as Stetho only in dev product flavor.

You can write a simple wrapper for each product flavor. This way, you can avoid including an unnecessary dependency to your Android apk.

build.gradle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
android {
    ...
    productFlavors {
        dev {
        }
        prod {
        }
    }
}
 
dependencies {
    ...
    devCompile 'com.facebook.stetho:stetho:1.4.1'
}

/app/src/dev/java/com/example/StethoWrapper.java:

1
2
3
4
5
6
7
public class StethoWrapper {
 
    public static void initializeWithDefaults(Application application) {
        Stetho.initializeWithDefaults(application);
    }
 
}

/app/src/prod/java/com/example/StethoWrapper.java:

1
2
3
4
5
6
7
public class StethoWrapper {
 
    public static void initializeWithDefaults(Application application) {
        // Not using Stetho for this product flavor
    }
 
}

/app/src/main/java/com/example/MyApplication.java

1
2
3
4
5
6
7
8
public class MyApplication extends Application {
 
    public void onCreate() {
        super.onCreate();
        StethoWrapper.initializeWithDefaults(this);
    }
 
}

Although debugging tools like LeakCanary provide a disabled version of library to be used for release apk, I prefer to use the approach above to completely exclude the dependency from my apk.

Leave a Comment