更新到 AGP(Android Gradle Plugin) 3.2.0 后,我们不能直接在 mergedFlavor
上设置 versionCode
。如果我们这样做,我们会得到这个有用的警告:
versionCode cannot be set on a mergedFlavor directly.
versionCodeOverride can instead be set for variant outputs using the following syntax:
android {
applicationVariants.all { variant ->
variant.outputs.each { output ->
output.versionCodeOverride = 40805
}
}
}
此更改后,除了一件小事外,一切正常。自动生成的 BuildConfig.VERSION_CODE
不反射(reflect)来自 output.versionCodeOverride = 40805
的版本代码。
在 AGP 3.2.0 之前,我们可以通过以下方式动态设置版本代码:
applicationVariants.all { v ->
v.mergedFlavor.versionCode = 40805 // 40805 is hardcoded as an example but it is archived dynamically.
}
BuildConfig.VERSION_CODE
中反射(reflect)了版本代码(这非常方便),我想使用 AGP 3.2.0 将其存档。
我知道我可以通过为此创建一个自定义构建配置字段来解决这个问题,例如 variant.buildConfigField('int', 'OVERRIDDEN_VERSION_CODE', "${versionCodeOverride}")
这将生成BuildConfig.OVERRIDDEN_VERSION_CODE
使用我覆盖的版本代码。通过 mergedFlavor.versionCode = 40805
设置 versionCode
来存档与我使用 3.2.0 以下 AGP 版本时相同,但我不喜欢这种解决方法。
有没有办法让 output.versionCodeOverride = 40805
反射(reflect)在自动生成的 BuildConfig.VERSION_CODE
中?
PS:如果我们直接在特定风格中设置 versionCode
,它将按预期工作,但这不是我想知道的:)
更新
发现了一个类似的问题(有一个很好描述的用例),考虑到我们的讨论,我可以给出更好的答案 here .
最佳答案
回顾一下,问题不在于根本没有应用版本代码覆盖,只是 BuildConfig.VERSION_CODE
没有获取覆盖值。
这已在官方问题跟踪器中标记为预期行为:https://issuetracker.google.com/issues/37008496
其中一条评论解释了原因并建议在 flavor 中定义 versionCode
而不是 defaultConfig
:
If we made a different buildconfig.java per output then we'd also need to run javac/proguard/jacoco/dex for each split and we'd lose the improvement in build [time].
If this is critical to you, then don't use splits and use flavors instead, but we'll get much slower build time.
如果您不想更改当前设置,您可能需要从 list 中读取版本代码。您只需要一个上下文:
val versionCode = context.packageManager.getPackageInfo(context.packageName, 0).versionCode
您应该缓存该值,因为获取包信息是一项非常重要的操作。
同样适用于版本名称。
关于android - 更新到 AGP 3.2.0 后,BuildConfig.VersionCode 未反射(reflect)实际版本代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52502548/