1.Android Studio 3.0之前:
在build.gradled 的 android {} 内添加如下代码:
android.applicationVariants.all { variant -> //如果是Library,例如aar包则使用 android.libraryVariants.all 且下面后缀判断修改为 .arr variant.outputs.each { output ->
def fileName = "demo_${defaultConfig.versionCode}-${defaultConfig.versionName}-${releaseTime()}.apk" def outputFile = output.outputFile if (outputFile != null && outputFile.name.endsWith('.apk')) { //这里修改apk文件名 output.outputFile = new File(outputFile.parent, fileName)
}
}
}
在 android {} 之外声明 releaseTime() 方法:
//获取编译时间 def releaseTime() { return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC")) }
2.Android Studio 3.0之后:
outputFile
变为只读,需把each
修改为all
,然后通过outputFileName
修改生成apk的名称,此外AS 3.0后打包完,除了apk包文件,还会多一个 output.json 参数文件。
新版修改如下:
//自定义apk名称含版本号信息
android.applicationVariants.all { variant ->
variant.outputs.all { output -> //旧版为:each
def fileName = "demo_${defaultConfig.versionCode}-${defaultConfig.versionName}-${releaseTime()}.apk"
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
//这里修改apk文件名
outputFileName = fileName //旧版为:output.outputFile = new File(outputFile.parent, fileName)
}
}
}
同样在 android {} 之外声明 releaseTime() 方法:
//获取编译时间 def releaseTime() { return new Date().format("yyyy-MM-dd", TimeZone.getTimeZone("UTC")) }
-end-