在android studio中执行自定义独立gradle任务

时间:2015-12-30 18:24:20

标签: android android-studio gradle android-gradle

我有一个包含多个模块的android项目。我试图从其中一个模块运行自定义gradle任务,但每次我在模块以及其他模块中运行任务所有其他gradle任务。我的任务不依赖于任何其他任务。任务:

task helloTask{
   println "Hello task"
}

我尝试通过工作室和命令行的终端窗口运行此任务。

4 个答案:

答案 0 :(得分:11)

Gradle将在配置阶段执行未使用<<声明的所有任务。如果您想将任务的执行延迟到执行阶段,那么您只需添加<<

即可

build.gradle

task helloConfiguration { task ->
    println "Hello configuration phase task! $task.name"
}

/* Notice the `<<` this denotes to gradle to not execute
 * the closure during the configuration phase. Instead
 * delay closure's execution till the execution phase.
 */
task helloExecution << { task ->
    println "Hello execution phase task! $task.name"
}

helloExecution.dependsOn helloConfiguration

然后在执行helloExecution任务时,我们看到两个都运行,确保顺序。接下来,如果我们只想运行配置构建的任务,我们可以根据需要单独执行,并且只运行单个任务。

$ gradle helloExecution
Hello configuration phase task! helloConfiguration
Hello execution phase task! helloExecution
:helloConfiguration UP-TO-DATE
:helloExecution UP-TO-DATE

BUILD SUCCESSFUL

Total time: 0.64 secs

$ gradle helloConfiguration
Hello configuration phase task! helloConfiguration
:helloConfiguration UP-TO-DATE

BUILD SUCCESSFUL

Total time: 0.784 secs

即使没有提供任务,也始终会执行在配置阶段运行的任务,这是我期望您看到的行为。所以给出上面的例子。注意配置任务已运行但未执行。

$ gradle
Hello configuration phase task! helloConfiguration
:help

Welcome to Gradle 2.10.

To run a build, run gradle <task> ...

To see a list of available tasks, run gradle tasks

To see a list of command-line options, run gradle --help

To see more detail about a task, run gradle help --task <task>

BUILD SUCCESSFUL

Total time: 0.651 secs

因此,如果您有5个在配置阶段运行的任务,那么您将看到所有这些任务都执行,无论命令行args是否尝试为执行阶段的目标调用该任务。

答案 1 :(得分:3)

在Android Studio中,调出Gradle视图(Android Studio窗口的右上角)

按Run Gradle Task(圆形按钮)。

从模块列表中选择包含build.gradle的模块,然后从任务列表中选择任务。

enter image description here


在Gradle视图树中,您的任务也会出现在YourModule/Tasks/other下,除非为任务明确指定了group

答案 2 :(得分:1)

您可以使用“运行配置”来实现相同目的。请参阅:https://developer.android.com/studio/run/rundebugconfig.html

转到Run - &gt;编辑配置 - &gt;单击+以添加新配置 - &gt;从出现的列表中选择Gradle。最后选择应用程序,然后键入要运行的任务。 Android Studio甚至可以为其提供自动填充功能。

稍后,运行该任务将直接作为选项在&#34;运行&#34;菜单。

答案 3 :(得分:0)

也许您没有给出正确的命令?

运行独立任务的过程:

  1. 向您的app/build.gradle文件添加任务。 例如:
task helloExecution { task ->
    doLast {
        println "Hello exececuted"
    }
}
  1. 导航到项目文件夹后,在终端上,键入./gradlew taskName
    例如:./gradlew helloExecution