【问题标题】:Android Gradle custom task per variant每个变体的 Android Gradle 自定义任务
【发布时间】:2015-05-22 18:47:02
【问题描述】:

我有一个使用 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

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

【问题讨论】:

    标签: android groovy gradle android-productflavors


    【解决方案1】:

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

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

    【讨论】:

    • 我是自己发现的 :( 还是谢谢你的提示!
    【解决方案2】:

    从 Gradle 3.2 开始,按照 Opal 的回答和 &lt;&lt; 运算符的 deprecation,正确答案应该是:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-17
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      相关资源
      最近更新 更多