Run task before compilation using Android Gradle plugin

The proper way to run a task before Java compilation on Android is to make a compilation task for each variant depend on your task.

afterEvaluate {
  android.applicationVariants.all { variant ->
    variant.javaCompiler.dependsOn(generateSources)
  }
}

You can see task execution in terminal running task for example gradle assemble. Try this one, it is started practically before anything.

android {
    ...
    gradle.projectsEvaluated {
         preBuild.dependsOn(generateSources)
    }
    ...
}

Edit, this may not work in Android Studio, as the Android Gradle DSL does not have a projectsEvaluated method.


Apparently, the android plugin doesn't add a compileJava task (like the java plugin would). You can check which tasks are available with gradle tasks --all, and pick the right one for your (otherwise correct) dependency declaration.

EDIT:

Apparently, the android plugin defers creation of tasks in such a way that they can't be accessed eagerly as usual. One way to overcome this problem is to defer access until the end of the configuration phase:

gradle.projectsEvaluated {
    compileJava.dependsOn(generateSources)
}

Chances are that there is a more idiomatic way to solve your use case, but quickly browsing the Android plugin docs I couldn't find one.