Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 408
Nicola Avatar asked Mar 19 '15 15:03

Nicola


People also ask

What is Buildtype in Gradle Android?

A build type determines how an app is packaged. By default, the Android plug-in for Gradle supports two different types of builds: debug and release . Both can be configured inside the buildTypes block inside of the module build file.

What is BuildConfig in Android?

BuildConfig is a class containing static constants that is included in every Android application. BuildConfig includes some default fields such as DEBUG and FLAVOR but you can also add custom values via build.

What is afterEvaluate in Gradle?

The afterEvaluate is useful in the root gradle file of a multi project build when you want to configure specific items based on the configuration made in subprojects. Say you want to add a task for all subprojects that have a specific plugin defined.


2 Answers

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()
    }
}
like image 161
Opal Avatar answered Sep 16 '22 14:09

Opal


Following Opal's answer and the deprecation of << operator since Gradle 3.2, the correct answer should be:

android.applicationVariants.all { variant ->
    task ("myCustomTask${variant.name.capitalize()}") {
        // This code runs at configuration time

        // You can for instance set the description of the defined task
        description = "Custom task for variant ${variant.name}"

        // This will set the `doLast` action for the task..
        doLast {
            // ..and so this code will run at task execution time
            println "*** TEST ***"
            println variant.name.capitalize()
        }
    }
}
like image 29
ovmjm Avatar answered Sep 17 '22 14:09

ovmjm