'Execute task before Android Gradle build?

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?



Solution 1:[1]

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

Solution 2:[2]

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 
}

Solution 3:[3]

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

Solution 4:[4]

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

Solution 5:[5]

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

Solution 6:[6]

This is Kotlin DSL (build.gradle.kts) equivalent of k_o_'s answer:

tasks.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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 nlawson
Solution 2 Volodymyr
Solution 3 k_o_
Solution 4 Vlad
Solution 5 Ben Watson
Solution 6