Gradle How to generate source code before compiling in an Android application

In my Android application, I need to generate the source code and use it in the application.
To do this, I created the genSources task (using tutorials) to generate the source. It works correctly if you run it separately.

In my case, I need to automatically generate the source code.

I learned the following command from the tutorial:

compileJava.dependsOn (genSources)

but this is an unknown command for an application using the plugin: 'com.android.library'
gradle throws the following exception:
Error:(35, 0) Could not find property 'compileJava' on project ':data'.

It looks like it can be used with the application plugin: "Java"
but i can't use these 2 plugins together

How can I solve this problem and create the necessary source code before compiling?

build.gradle

 apply plugin: 'com.android.library' configurations {pmd} android { compileSdkVersion 21 buildToolsVersion "21.1.2" defaultConfig { minSdkVersion 19 targetSdkVersion 21 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } buildscript { repositories { maven { url "http://repo1.maven.org/maven2/" } } dependencies { classpath group: 'net.sourceforge.fmpp', name: 'fmpp', version: '0.9.14' } ant.taskdef(name: 'fmpp', classname:'fmpp.tools.AntTask', classpath: buildscript.configurations.classpath.asPath) } task genSources << { println "Generating sources...." ant.fmpp configuration:"src/main/resources/codegen/config.fmpp", sourceRoot:"src/main/resources/codegen/templates", outputRoot:"target/generated-sources/main/java"; } compileJava.dependsOn(genSources) sourceSets { main { java { srcDir 'target/generated-sources/main/java' } } } dependencies { ... } 

UPDATED

I found some solution that at least doesn't throw an exception

 gradle.projectsEvaluated { compileJava.dependsOn(genSources) } 

Then I do gradle build but nothing happens

+7
android gradle
source share
1 answer

With gradle 2.2+, this should work:

 tasks.withType(JavaCompile) { compileTask -> compileTask.dependsOn genSources } 

If you also want this to happen when you evaluate (for example, when synchronizing a project with gradle in android studio), you can do it like this:

 gradle.projectsEvaluated { preBuild.dependsOn genSources } 
+8
source share

All Articles