How to run a task before build in 2021 gradle Kotlin syntax in an Android project

Viewed 1347

I read a lot of answers to multiple questions like this, but they are all very old and use arcane/obsolete syntax in groovy and/or are not suitable for Android projects.

I have a task.

tasks.register("asd") {
  doFirst {
    exec {

How do I run it when build starts in an Android app/build.gradle.kts file?

I have printed both tasks and project.tasks names and I have tried

tasks.named("build").dependsOn(":asd")
tasks.named("app:build").dependsOn(":asd")
tasks.named(":app:build").dependsOn(":asd")
project.tasks.named("build").dependsOn(":asd")
project.tasks.named("app:build").dependsOn(":asd")
project.tasks.named(":app:build").dependsOn(":asd")

It either fails with Task <name> not found in project or it does nothing.

I tried with doFirst, doLast and neither (directly exec) and still nothing.

1 Answers

So I found the right way to go about it

android {
  project.tasks.preBuild.dependsOn("asd") 
}


tasks.register("asd") {
  doFirst {
    exec {


No need for the : when referring to the task. The build and preBuild tasks are accessible from (project.)tasks.

doFirst was necessary otherwise it would loop endlessly. tasks.register allowed the task to run when it needed and not immediately, which happens if we use create

Related