How to get current buildType in Android Gradle configuration

Solution 1:

You can use

if (gradle.startParameter.taskNames.contains("assembleExample")) {
    // do stuff
}

That variable will be set before the buildConfig block is evaluated

Solution 2:

I could not find a clean way to get the current build type during the configuration phase of Gradle. Instead I define the dependency for each build type separately like that:

debugCompile project(path: ':lib1', configuration: 'debug')
releaseCompile project(path: ':lib1', configuration: 'release')

If you have many build types and many project dependencies this can get very verbose, but it is possible to add a function to make the dependency a one-liner. You need to add this to your main Gradle build file:

subprojects {
    android {
        dependencies.metaClass.allCompile { dependency ->
            buildTypes.each { buildType ->
                "${buildType.name}Compile" project(path: ":${dependency.name}", configuration: buildType.name)
            }
        }
    }
}

Then you can add project dependencies in your Gradle modules like this:

allCompile project(':lib1')

If you also use build flavors you would have to adapt the solution. See this link for a documentation of the feature: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Library-Publication

Please note that the Android team is working on an improvement for this behaviour: https://code.google.com/p/android/issues/detail?id=52962