使用 gradle 插件 3 的文件中的版本名称和代码

Version name and code from files with gradle plugin 3

我的 android 构建设置为在发布模式下使用文件中的 versionNameversionCode。在不创建发布构建以保持增量构建工作时,它们被设置为静态值。

gradle 文件的相关部分是:

android {
    defaultConfig {
        versionCode 1
        versionName "1.0"
        // SNIP...
    }

    applicationVariants.all { variant ->
        if (variant.buildType.name == "release") {
            variant.versionCode = file('version-code.txt').text as int
            variant.versionName = file('version.txt').text
        }
    }

    // SNIP ...
}

版本文件的示例内容可以是:

这是通过遵循推荐指南中的 Use static build config values with your debug build 部分来完成的,以保持增量构建正常工作。

For example, using dynamic version codes, version names, resources, or any other build logic that changes the manifest file requires a full APK build every time you want to run a change—even though the actual change might otherwise require only a hot swap. If your build configuration requires such dynamic properties, then isolate them to your release build variants and keep the values static for your debug builds, as shown in the build.gradle file below.

但是,我们发现自从升级到 gradle 插件的第 3 版后,此功能已失效,该插件不再有效。 gradle 插件 3.0.0 迁移指南的 Modifying variant outputs at build time may not work 部分说:

Using the Variant API to manipulate variant outputs is broken with the new plugin. It still works for simple tasks, such as changing the APK name during build time, as shown below:

However, more complicated tasks that involve accessing outputFile objects no longer work. That's because variant-specific tasks are no longer created during the configuration stage. This results in the plugin not knowing all of its outputs up front, but it also means faster configuration times.

迁移指南中似乎没有推荐任何替代方案。还有其他方法可以实现吗?

更新

感谢@nhoxbypass 的回答,将我的 gradle 文件更改为包含以下内容让事情再次发生:

applicationVariants.all { variant ->
    if (variant.buildType.name == "release") {
        variant.outputs.all { output ->
            output.setVersionNameOverride(file('version.txt').text)
            output.setVersionCodeOverride(file('version-code.txt').text as int)
        }
    }
}

migration guide对于简单的任务仍然有效,例如在构建期间更改 APK 名称(至少对我的项目有效)。但是,涉及访问 outputFile 对象的更复杂任务不再有效。

但是如果您需要尝试一种解决方法,在 3.0 版本之前已经存在一个解决方法,如果有人正在寻找解决方案,您可以使用:

output.setVersionCodeOverride(Integer.parseInt(buildTimeSmall()))

参见:Unable to change project versionCode for different build types