Execute task before Android Gradle build?

102.9k Views Asked by At

is it possible for Gradle to execute a task before calling

gradle build

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

7

There are 7 best solutions below

6
pepuch On BEST ANSWER

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
nlawson On

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
5
Volodymyr On

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 
}
0
Ben Watson On

If the task to be run is already defined (for example publishToMavenLocal), you can add it into your gradle build task with:

build.dependsOn publishToMavenLocal
0
Vlad On

In Gradle 5.4.x

// File: app/build.gradle
// See: https://docs.gradle.org/current/dsl/org.gradle.api.tasks.Exec.html
task ruby(type:Exec) {
    workingDir '../'
    executable = '/usr/bin/env'
    args = ["ruby", "--version"]
}
preBuild.dependsOn ruby
4
k_o_ On

The left shift operator << was removed in Gradle 5.

In my case I had an Android project using a Java sub project and this worked:

task myTask {
    doLast {
        println 'do it before build'
    }
}

assemble.dependsOn myTask

Regarding the initial question this should be the syntax now:

task myTask {
    doLast {
        println 'do it before build'
    }
}
build.dependsOn myTask
// or for Android
preBuild.dependsOn myTask
0
Mahozad On

This is for Kotlin DSL (build.gradle.kts):

tasks.register/* OR .create */("MyTask") {
    doLast {
        println("I am the task MyTask")
    }
}

tasks.build {
    dependsOn("MyTask")
}

// OR another notation
// tasks.named("build") {
//     dependsOn(tasks["MyTask"])
// }

For more information see Gradle documentation: Adding dependencies to a task.