Build variants in Gradle for a Library Project in Android

Javier Tarazaga picture Javier Tarazaga · Jul 3, 2013 · Viewed 14.4k times · Source

I am trying to configure with Gradle a project which contains some external libraries. With Gradle I can setup different Environmental Configuration (with a class inside a config file) for the main application using the Build Variants so I can execute code according to this variables.

The problem is that how I can do the same for a library project? I created this library for this project and I would like to setup different Build Variants for different scenarios.

As an example: In the Library, when running in debug mode, then print all the logs so I can see them while developing. In release mode dont.

Structure of the files:

src ----- > debug -> java -> config -> PlayerEnvConfig
            main -> com.mypackagename -> etc...
            release -> java -> config -> PlayerEnvConfig

Code in debug: package config;

/**
 * Environment configuration for Release
*/
public final class PlayerEnvConfig {
    public static final boolean USE_REPORTING = true;
    public static final boolean USE_ANALYTICS = true;
    public static final boolean USE_LOGGING = false;
    public static final boolean USE_DEBUG_LOGGING = false;
    public static final boolean USE_DEBUGING = false;
}

Code in release:

package config;

/**
 * Environment configuration for Release
*/
public final class PlayerEnvConfig {
    public static final boolean USE_REPORTING = true;
    public static final boolean USE_ANALYTICS = true;
    public static final boolean USE_LOGGING = false;
    public static final boolean USE_DEBUG_LOGGING = false;
    public static final boolean USE_DEBUGING = false;
}

The problem is that for the main project I can use this Build types to configure differently the application for different scenarios, but how can I do the same for the Library Project?

Because at the moment from what I read in http://tools.android.com/tech-docs/new-build-system/user-guide the library only will use the debug mode while testing.

Any ideas?

Thanks!

Answer

Beloo picture Beloo · Sep 25, 2014

It's a @bifmadei answer from google code issue and it helps for me:

Obsolete: Try setting this in the dependency project

android {
    publishNonDefault true
    ...
}

Update: Starting from gradle 4.10.1 publishNonDefault is true by default. So just use the recommendation below:

Include this in the project that uses it

dependencies {
    releaseCompile project(path: ':theotherproject', configuration: 'release')
    debugCompile project(path: ':theotherproject', configuration: 'debug')
}

Taken from here: https://code.google.com/p/android/issues/detail?id=66805

New approach: Note that with implementation instruction separated releaseCompile and debugCompile become obsolete: https://stackoverflow.com/a/44364851/3379437

But this approach still can be used with a custom build configuration