我们有这需要一定的摇篮插件任务运行我们所建立的APK之前的Android项目。 (该插件是由我们写的)
我们希望每一个构建之前自动运行任务。
如果我们使用过时task.execute()
那么我们得到的,这将是不可用的版本开始,5.0或类似的东西警告。
如果我们使用dependsOn
推荐,然后testTask1
是不能建立之前,但干净后只。 (所有的评论下面解释)
我一直在gradle这个文档,和许多其他SO线程,但我还没有找到一个解决方案。
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
flatDir { dirs 'libs' }
jcenter()
google()
}
dependencies {
classpath "com.android.tools.build:gradle:3.1.3"
// our platform-tools plugin, in charge of some gradle tasks
classpath 'sofakingforevre:test-plugin:1.0-SNAPSHOT'
}
}
apply plugin: 'test-plugin'
allprojects {
repositories {
jcenter()
google()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
// OPTION 1 - USING EXECUTE()
// this task works as expected when calling "clean", but also when calling "assemble".
// the problem here is that the "execute" method has been deprecated, and we want to prepare for Gradle 5.0
// CLEAN - testTask1 is called :)
// BUILD - testTask1 is called :)
// DEPRECATION WARNING :(
task buildPlatformExecute {
println("executing")
// this task is created by the plugin
tasks.getByName("testTask1").execute()
}
clean.dependsOn buildPlatformExecute
// OPTION 2 - USING DEPENDSON()
// this tasks works as expected when calling "clean", but DOES NOT WORK when calling "assemble".
// If we call we call assemble, the "executing" text does print, but "testTask1" would not run.
// CLEAN - testTask1 is called :)
// BUILD - testTask1 is NOT CALLED :(
task buildPlatformDependency {
println("executing")
// this task is created by the plugin
dependsOn 'testTask1'
}
clean.dependsOn buildPlatformDependency
与OPTION 1解决的问题
task.execute()
API(你已经意识到这一点)因为你没有在tasks.getByName("testTask1").execute()
任务doLast {}
块的doFirst {}
包裹buildPlatformExecute
:在testTask1
任务就一定会执行,不管任务中,您将调用。你甚至都不需要创建clean
任务和自定义任务之间的依赖关系(例如:尝试执行简单的“帮助”任务with./gradlew help
你将看到的是也执行该testTask1
:这肯定不是你想要的)
点击此处了解详情:https://docs.gradle.org/current/userguide/build_lifecycle.html
问题与解决方案OPTION2
你创造了clean
任务andbuildPlatformDependency
任务之间的依赖关系:
clean
任务时,如预期testTask1
任务将被执行,但build
(或assemble
)任务和clean
任务之间不存在相关性:这就是为什么当你执行任务build
,不执行clean
任务(所以testTask1
不会被触发)解
最好的办法是钩你自定义任务testTask1
在你的项目构建生命周期中的正确位置,使用Task.dependsOn
API。 “正确”的位置取决于你的任务是负责在构建过程:例如,如果你的工作需要进行前assemble
任务执行,只需创建依赖assemble.dependsOn testTask1