如何使用0.14+版本的Android Gradle插件为我的APK文件添加版本号?

Arg*_*yle 8 android gradle

我希望versionName从我的Android版本中包含输出APK文件的名称.

还有一个适用于0.14.x之前的插件版本的答案,但他们改变了一些数据模型,因此不再起作用,我无法弄清楚如何修复它.据我所知,下面的代码块应该可以工作,但最后一次set()调用似乎没有效果.它不会抛出错误,但也不会替换该值.

buildTypes {
    applicationVariants.all { variant ->
        def oldFile = variant.outputs.outputFile.get(0)
        def newFile = new File(
                oldFile.parent,
                oldFile.name.replace(".apk", "-" + defaultConfig.versionName + ".apk"))

        variant.outputs.outputFile.set(0, newFile)
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题吗?

kco*_*ock 23

现在每个变体可以有多个输出,您还需要一个循环:

android {
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            output.outputFile = new File(
                    output.outputFile.parent,
                    output.outputFile.name.replace(".apk", "-${variant.versionName}.apk"))
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • ......这就是我们不喜欢gradle的原因.你必须编写代码来改变令人讨厌的输出文件名. (4认同)
  • 我收到一个错误,说它无法找到applicationVarients属性 (3认同)

gnu*_*nuf 8

使用 3.0.0 或更高版本的插件时,您必须稍作更改:

applicationVariants.all { variant ->
    variant.outputs.all { output ->
        outputFileName = "myapp-${variant.versionName}-${variant.name}.apk"
    }
}
Run Code Online (Sandbox Code Playgroud)

3.0.0 插件迁移文档说:

如果使用 each() 遍历变体对象,则需要开始使用 all()。这是因为 each() 仅迭代配置期间已存在的对象,但这些对象在配置时不存在新模型。但是, all() 通过在执行期间添加对象时拾取对象来适应新模型。