Run task before compilation using Android Gradle plugin

北城余情 提交于 2019-11-26 22:13:04

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.

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)
  }
}
Gennadiy Ryabkin

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

gradle.projectsEvaluated {
     preBuild.dependsOn(generateSources)
}

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

Try this:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.4.1'
    }
}

apply plugin: 'android'

android {
    buildToolsVersion "17.0.0"
    compileSdkVersion 17

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
    }
}

task generateSources {
    def script = "python GenerateSources.py".execute()
    script.in.eachLine {line -> println line}
    script.err.eachLine {line -> println "ERROR: " + line}
    script.waitFor()
}

project.afterEvaluate {
    preBuild.dependsOn generateSources
}

clean.dependsOn generateSources
clean.mustRunAfter generateSources

The last two lines are optional - they will invoke the "generateSources" task when executing a gradle clean

For those having a multi-project build and needing to run a task for each project before they're built (but it should also be ok if you have only the app project), you can write the task in the root build configuration script inside the allprojects closure and executing the task right there.

In root project build.gradle:

allprojects {
    repositories {
        // ...
    }
    // ...
    task mytask {
        doFirst {
            println project.projectDir.name
        }
    }
    mytask.execute()
}

It will be executed for every build variant as well.

Gradle 4.1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!