之前在旧版本Android Studio中用以下代码修改过release版本的apk名:
applicationVariants.all { variant ->
variant.outputs.each { output ->
def SEP = "_"
def flavor = variant.productFlavors[0].name
def buildType =
variant.variantData.variantConfiguration.buildType.name
def version = variant.versionName
def date = new Date()
def formattedDate = date.format('ddMMyy_HHmm')
def newApkName = PROJECT_NAME + SEP + flavor + SEP + buildType + SEP + version + SEP + formattedDate + ".apk"
def file = new File(newApkName)
output.outputFile = file
}
}
然而升级Android Studio 3.0 后编译不通过,并报了以下错误:
Cannot set the value of read-only property ‘outputFile’ for ApkVariantOutputImpl_Decorated{apkData=Main{type=MAIN, fullName=debug, filters=[]}} of type com.android.build.gradle.internal.api.ApkVariantOutputImpl.
原因
Android Studio 3.0 修改了打包规则,详细规则见 Android plugin 3.0 migration guide(需翻墙)
解决方法
使用 all() 替换 each()
使用 outputFileName 替换 output.outputFile
示例
// If you use each() to iterate through the variant objects,
// you need to start using all(). That's because each() iterates
// through only the objects that already exist during configuration time—
// but those object don't exist at configuration time with the new model.
// However, all() adapts to the new model by picking up object as they are
// added during execution.
android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${variant.name}-${variant.versionName}.apk"
}
}