Run clean task before every build automatically in Gradle

7.8k views Asked by At

I want to run a project "clean" before the assembleRelease task in Gradle.

How can I trigger the clean task basically before everything?

3

There are 3 answers

3
Gabriele Mariotti On

In gradle you can use the dependsOn method.

B.dependsOn A

In this way:

  • task B depends on task A
  • gradle executes A task everytime before the B task execution.

In your case:

assembleRelease.dependsOn clean
1
reidisaki On

Adding to this, what I needed to do was have this in the

    android {
    afterEvaluate { 
       assemble(*your task here*)debug clean
}

and now it works great

0
shizhen On

Use following code to execute the clean task first per each build variant

project.afterEvaluate {
    android.applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def capitalizedVariant = variant.name.capitalize()
            def assembleVariantTask = project.tasks."assemble${capitalizedVariant}"
            assembleVariantTask.dependsOn clean
        }
    }
}