自定义版本号通仅能在flavor操作,但是无法对buildType。
原因是在mVersionCode和mVersionName等属性是在DefaultProductFlavor.java
之前有方案是:
applicationVariants.all { applicationVariant ->
applicationVariant.outputs.each { output ->
if(applicationVariant.buildType.name == 'release') {
applicationVariant.mergedFlavor.versionName = '2.4.3'
}
}
}
但此方案在gradle3.0后不再支持,会报
> com.android.builder.errors.EvalIssueException:
versionName cannot be set on a mergedFlavor directly.
versionNameOverride can instead be set for variant outputs using the following syntax:
原因是在MergedFlavor.setVersionName的时候会报出异常:
override fun setVersionName(versionName: String?): ProductFlavor {
// calling setVersionName results in a sync Error because the manifest merger doesn't pick
// up the change.
reportErrorWithWorkaround("versionName", "versionNameOverride", versionName)
return this
}
private fun reportErrorWithWorkaround(
fieldName: String, outputFieldName: String, fieldValue: Any?) {
val formattedFieldValue = if (fieldValue is String) {
"\"" + fieldValue + "\""
} else {
fieldValue.toString()
}
val message = """
$fieldName cannot be set on a mergedFlavor directly.
$outputFieldName can instead be set for variant outputs using the following syntax:
android {
applicationVariants.all { variant ->
variant.outputs.each { output ->
output.$outputFieldName = $formattedFieldValue
}
}
}"""
issueReporter.reportError(EvalIssueReporter.Type.GENERIC,
EvalIssueException(message))
}
因此,可以用下面的方法:
applicationVariants.all { applicationVariant ->
applicationVariant.outputs.each { output ->
if(applicationVariant.buildType.name == 'release') {
output.setVersionNameOverride('2.4.3')
output.setVersionCodeOverride(20403)
}
}
}
原理是:
getOutputs接口由ApkVariantOutput接口实现,而ApkVariantOutput的接口如下:
而setVersionCodeOverride的实现如下:
@Override
public void setVersionCodeOverride(int versionCodeOverride) {
apkData.setVersionCode((IntSupplier & Serializable) () -> versionCodeOverride);
}
由此可以实现apk不同flavor和buildType的versionName和versionCode的自定义