vetalitet
vetalitet

Reputation: 703

Gradle. How to generate source code before compilation in android app

In my android application I need to generate source code and use it in the app.
For that I created task genSources (using tutorials) for source generation. It works correctly if run it separately.

In my case I need to run source code generation automatically.

From tutorial I found out the following command:

compileJava.dependsOn(genSources)

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

Looks like it can be used with apply plugin: 'Java'
but I cannot use these 2 plugins together

How can I solve this issue and generate needed source code before compilation?

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 was found some solution which at least not throw exception

gradle.projectsEvaluated {
    compileJava.dependsOn(genSources)
}

Then I execute gradle build but nothing happens

Upvotes: 12

Views: 11022

Answers (2)

TWiStErRob
TWiStErRob

Reputation: 46460

In the post AGP 8 "new variant API", the syntax is:

androidComponents.onVariants { variant ->
    val taskProvider = project.tasks
        .register<MyGeneratingTask>("generate${variant.name}FooBarSources") {
            myOutput.set(...)
        }
    variant.sources.java?.addGeneratedSourceDirectory(taskProvider, MyGeneratingTask::myOutput)
}

See https://github.com/android/gradle-recipes/tree/agp-8.0/Kotlin/addJavaSourceFromTask for an official example.


In the AGP pre-7/8 variant API (do not use unless you have to support old versions!):

android.applicationVariants.all { ApplicationVariant variant ->
    File out = ...
    def taskProvider = project.tasks
        .register("generate${variant.name}FooBarSources", MyGeneratingTask, { MyGeneratingTask task ->
            task.myOutput.set(out)
        })
    variant.registerJavaGeneratingTask(sourceTaskProvider, javaOutputDir)  
}

See for more details: https://medium.com/swlh/generating-java-kotlin-source-files-during-android-gradle-build-db6161674afc

and see https://github.com/android/gradle-recipes/tree/agp-7.4/Kotlin/addJavaSourceFromTask for an official example.


In both cases the custom task has a shape similar to this:

abstract class MyGeneratingTask : DefaultTask() {

    @get:OutputDirectory
    abstract val myOutput: DirectoryProperty

    @TaskAction fun generate() {
        // Use myOutput.get() and populate contents however necessary.
    }
}

Upvotes: 1

Zarokka
Zarokka

Reputation: 3056

With gradle 2.2+ this should work:

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

If you also want it to happen when you evaluate (e.g. when syncing your project with gradle in android studio) you can do it like this:

gradle.projectsEvaluated {
    preBuild.dependsOn genSources
}

Upvotes: 17

Related Questions