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
}
or this
afterEvaluate {
task myTaskOnlyForDebugBuildType(dependsOn:assembleDebug) {
//do smth
}
}
But both didn't work for me.
Here is a full example on how to do this inspired by this post: (android plugin v.0.9.2 and gradle 1.11 at the time of writing)
We are going to define a task that only runs when we build a "debugCustomBuildType"
android {
...
buildTypes {
debugCustomBuildType {
//config
}
}
}
Define the task that should only be executed on a specific builtType/variant/flavor
task doSomethingOnWhenBuildDebugCustom {
doLast {
//task action
}
}
Dynamically set the dependency when the tasks are added by gradle
tasks.whenTaskAdded { task ->
if (task.name == 'generateDebugCustomBuildTypeBuildConfig') {
task.dependsOn doSomethingOnWhenBuildDebugCustom
}
}
Here we use the "generateBuildConfig" task, but you can use any task that works for you (also see official docs)
- processManifest
- aidlCompile
- renderscriptCompile
- mergeResourcess.
- mergeAssets
- processResources
- generateBuildConfig
- javaCompile
- processJavaResources
- assemble
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.
I achieved it like this:
android {
ext.addDependency = {
task, flavor, dependency ->
def taskName = task.name.toLowerCase(Locale.US)
if (taskName.indexOf(flavor.toLowerCase(Locale.US)) >= 0) {
task.dependsOn dependency
}
}
productFlavors {
production {
}
other
}
task theProductionTask << {
println('only in production')
}
tasks.withType(JavaCompile) {
compileTask -> addDependency compileTask, "production", theProductionTask
}
}
To be frank, I don't which locale is used to generate names for compile taks so toLowerCase(Locale.US)
may be counterproductive.
This is the only solution that worked for me:
afterEvaluate {
if (project.hasProperty("preReleaseBuild")){
tasks.preReleaseBuild.dependsOn bundleJSRelease
} else {
tasks.preDebugBuild.dependsOn bundleJSDebug
}
}
tasks.whenTaskAdded { task ->
if (task.name.contains("assembleRelease")) {
task.getDependsOn().add({
// add your logic here
})
}
}
来源:https://stackoverflow.com/questions/22743663/in-android-gradle-how-to-define-a-task-that-only-runs-when-building-specific-bui