本文介绍了在 Android/Gradle 中如何定义仅在构建特定 buildType/buildVariant/productFlavor (v0.10+) 时运行的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Android Plugin for Gradle 为每个 BuilType/Flavor/BuildVariant 生成一个任务.问题是这个任务是动态生成的,因此在定义这样的任务时不能作为依赖项使用:

Android Plugin for Gradle generates for every BuilType/Flavor/BuildVariant a task. The problem is that this task will be generated dynamically and thus won't be available as a dependency when defining a task like this:

task myTaskOnlyForDebugBuildType(dependsOn:assembleDebug) {
    //do smth
}

答案的建议解决方法是这样的

A proposed workaround from this answer would be this

task myTaskOnlyForDebugBuildType(dependsOn:"assembleDebug") {
    //do smth
}

或者这个

afterEvaluate {
    task myTaskOnlyForDebugBuildType(dependsOn:assembleDebug) {
        //do smth
    }
}

但两者都不适合我.

推荐答案

这里有一个完整的例子说明如何做到这一点受这篇文章启发: (当时的android插件v.0.9.2和gradle 1.11写作)

我们将定义一个仅在构建debugCustomBuildType"时运行的任务

We are going to define a task that only runs when we build a "debugCustomBuildType"

android {
    ...
    buildTypes {
        debugCustomBuildType {
            //config
        }
   }
}

定义只应在特定的builtType/variant/flavor 上执行的任务

Define the task that should only be executed on a specific builtType/variant/flavor

task doSomethingOnWhenBuildDebugCustom {
    doLast {
       //task action
    }
}

gradle添加任务时动态设置依赖

Dynamically set the dependency when the tasks are added by gradle

tasks.whenTaskAdded { task ->
    if (task.name == 'generateDebugCustomBuildTypeBuildConfig') {
        task.dependsOn doSomethingOnWhenBuildDebugCustom
    }
}

这里我们使用generateBuildConfig"任务,但您可以使用任何适合您的任务(另见官方文档)

Here we use the "generateBuildConfig" task, but you can use any task that works for you (also see official docs)

  • 流程清单
  • aidl编译
  • renderscriptCompile
  • 合并资源.
  • 合并资产
  • 处理资源
  • 生成构建配置
  • java编译
  • 处理Java资源
  • 组装

别忘了使用 buildTypeSpecific 任务(generateBuildConfig vs. generateDebugCustomBuildTypeBuildConfig)

Don't forget to use the buildTypeSpecific task (generateBuildConfig vs. generateDebugCustomBuildTypeBuildConfig)

就是这样.遗憾的是,这种解决方法没有得到很好的记录,因为对我来说,这似乎是构建脚本最简单的要求之一.

And that's it. It's a shame this workaround isn't well documented because for me this seems like one of the simplest requirements for a build script.

这篇关于在 Android/Gradle 中如何定义仅在构建特定 buildType/buildVariant/productFlavor (v0.10+) 时运行的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 20:34
查看更多