Search code examples
androidgroovygradleandroid-productflavors

Android Gradle custom task per variant


I have an Android app built with Gradle, which contains BuildTypes and Product Flavors (variants). I can for example run this command to build a specific apk:

./gradlew testFlavor1Debug
./gradlew testFlavor2Debug

I have to create a custom task in the build.gradle per variant, for example:

./gradlew myCustomTaskFlavor1Debug

I have created a task for this:

android.applicationVariants.all { variant ->
    task ("myCustomTask${variant.name.capitalize()}") {
        println "*** TEST ***"
        println variant.name.capitalize()
    }
}

My problem is that this task is called for ALL the variants, not the only one I am running. Output:

./gradlew myCustomTaskFlavor1Debug

*** TEST ***
Flavor1Debug
*** TEST ***
Flavor1Release
*** TEST ***
Flavor2Debug
*** TEST ***
Flavor2Release

Expected output:

./gradlew myCustomTaskFlavor1Debug

*** TEST ***
Flavor1Debug

How can I define a custom task, dynamic, per variant, and then call it with the right variant?


Solution

  • It happens because the logic is executed at configuration time. Try adding an action (<<):

    android.applicationVariants.all { variant ->
        task ("myCustomTask${variant.name.capitalize()}") << {
            println "*** TEST ***"
            println variant.name.capitalize()
        }
    }