Android Gradle 每个变体的自定义任务

Android Gradle custom task per variant

我有一个 Android 使用 Gradle 构建的应用程序,其中包含 BuildTypes 和 Product Flavors(变体)。 例如,我可以 运行 这个命令来构建一个特定的 apk:

./gradlew testFlavor1Debug
./gradlew testFlavor2Debug

我必须在每个变体 build.gradle 中创建一个自定义任务,例如:

./gradlew myCustomTaskFlavor1Debug

我为此创建了一个任务:

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

我的问题是这个任务是为所有变体调用的,而不是我 运行ning 的唯一一个。 输出:

./gradlew myCustomTaskFlavor1Debug

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

预期输出:

./gradlew myCustomTaskFlavor1Debug

*** TEST ***
Flavor1Debug

我如何为每个变体定义一个动态的自定义任务,然后使用正确的变体调用它?

发生这种情况是因为逻辑在配置时执行。尝试添加一个动作 (<<):

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

根据 Opal 的回答和 << 运算符的 deprecation 自 Gradle 3.2 以来,正确答案应该是:

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()
        }
    }
}