for3st for3st - 1 year ago 103
Android Question

In Android/Gradle how to define a task that only runs when building specific buildType/buildVariant/productFlavor (v0.10+)

Android Plugin for Gradle generates for every BuilType/Flavor/BuildVariant a task. The problem is that this task will be generated dynamically and thus won't be available as a dependency when defining a task like this:

task myTaskOnlyForDebugBuildType(dependsOn:assembleDebug) {
//do smth

A proposed workaround from this answer would be this

task myTaskOnlyForDebugBuildType(dependsOn:"assembleDebug") {
//do smth

or this

afterEvaluate {
task myTaskOnlyForDebugBuildType(dependsOn:assembleDebug) {
//do smth

But both didn't work for me.

Answer Source

Here is a full example on how to do this inspired by this post: (android plugin v.0.9.2 and gradle 1.11 at the time of writing)

We are going to define a task that only runs when we build a "debugCustomBuildType"

android {
    buildTypes {
        debugCustomBuildType {

Define the task that should only be executed on a specific builtType/variant/flavor

task doSomethingOnWhenBuildDebugCustom << {
    //task action

It's important to use the << left-shift syntax to add the task action or else the task automatically will be called everytime.

Dynamically set the dependency when the tasks are added by gradle

tasks.whenTaskAdded { task ->
    if ( == 'generateDebugCustomBuildTypeBuildConfig') {
        task.dependsOn doSomethingOnWhenBuildDebugCustom 

Here we use the "generateBuildConfig" task, but you can use any task that works for you (also see official docs)

  • processManifest
  • aidlCompile
  • renderscriptCompile
  • mergeResourcess.
  • mergeAssets
  • processResources
  • generateBuildConfig
  • javaCompile
  • processJavaResources
  • assemble

Don't forget to use the buildTypeSpecific task (generateBuildConfig vs. generateDebugCustomBuildTypeBuildConfig)

And that's it. It's a shame this workaround isn't well documented because for me this seems like one of the simplest requirements for a build script.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download