采用Android摇篮插件编译之前运行的任务摇篮、插件、任务、Android

2023-09-12 22:53:20 作者:毕业了、我们就散了

我有一个非常简单的 build.gradle ,其内容如下文件:

I have a very simple build.gradle file with the following content:

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 {
    doFirst {
        def script = "python GenerateSources.py".execute()
        script.in.eachLine {line -> println line}
        script.err.eachLine {line -> println "ERROR: " + line}
        script.waitFor()
    }
}

我要的是Java编译开始前运行 generateSources 任务。我发现了几个解决方案,如何做到这一点,如 compileJava.dependsOn(generateSources),但不幸的是他们给了一个错误:

What I want is to run generateSources task before java compilation is started. I found several solutions how to do that, like compileJava.dependsOn("generateSources"), but unfortunately they give an error:

A problem occurred evaluating root project 'Android'.
> Could not find property 'compileJava' on root project 'Android'.

我不知道摇篮,搞不懂这有什么错这个code。所以,我想知道我可以修复这个错误。

I don't know Gradle and can't understand what's wrong with this code. So I would like to know how I can fix this error.

推荐答案

显然,机器人插件不添加 compileJava 的任务(如的Java 插件会)。您可以检查哪些任务可以用摇篮任务 - 所有,并选择最适合贵(否则正确的)依赖性声明。

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.

编辑:

显然,机器人插件推迟创建任务的这样一种方式,他们不能被急切地访问如常。克服这个问题的方法之一是延迟访问,直到结束时的配置相的

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

有机会,有一个更惯用的方式来解决你的使用情况,但很快浏览的 Android插件文档我无法找到一个。

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.