安卓Gradle:每个变种自定义任务

15

我有一个使用Gradle构建的Android应用程序,其中包含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()
    }
}

我的问题是这个任务被称为“所有”变量,而不仅仅是我正在运行的那一个。

./gradlew myCustomTaskFlavor1Debug

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

期望输出:

./gradlew myCustomTaskFlavor1Debug

*** TEST ***
Flavor1Debug

我如何定义一个自定义任务,动态地、针对每个变体,并使用正确的变体来调用它?

2个回答

18

这是因为逻辑是在配置时间执行的。尝试添加一个操作(<<):

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

我刚刚自己发现了它 :( 无论如何,还是谢谢你的提示! - Nicola

4

在 Opal 的答案和自 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()
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接