execute task before android gradle build?

2019-01-11 12:28发布

问题:

is it possible to gradle to execute task before calling

gradle build

something like precompile. Someone please help. Is something like this posible and how?

回答1:

You can do it in this way:

task build << {
    println 'build'
}
task preBuild << {
    println 'do it before build'
}
build.dependsOn preBuild

Thanks to that task preBuild will be automatically called before build task.

If you want to run preBuild in configuration phase (previous example run preBuild in execution phase) you can do it in this way:

task build << {
    println 'build'
}
build.doFirst {
    println 'do it before build'
}

More about gradle build lifecycle can be read here http://www.gradle.org/docs/current/userguide/build_lifecycle.html.



回答2:

For those who are wondering how to do this in an Android project, this worked for me:

task myTask << {
  println "here's a task"
}
preBuild.dependsOn myTask


回答3:

There is one more way how to do this

task myTask << {
    println "here's a task"
}
tasks.whenTaskAdded { task ->
if (task.name == 'assembleDebug') {
    task.dependsOn myTask 
}