有些时候我们需要将打包出来的安卓 Apk 名字改成 git 的 hash 值,这样在出现问题的时候通过 git 回溯到 Apk 打包出来的提交点,快速找到出错的位置,从而解决这个问题。
app/build.gradle
def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
android {
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
//这里修改apk文件名
def fileName = outputFile.name.replace("app", "test-${gitSha}")
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
}
该实现方法在 gradle 2.2.3 的时候还有效,升级到 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.
即 outputFile 只是可读的了。
Android plugin 3.0 建议使用 Use all() instead of each()。
Use outputFileName instead of output.outputFile if you change only file name (that is your case)
修改之后的 app/build.gradle如下。
def gitSha = 'git rev-parse --short HEAD'.execute([], project.rootDir).text.trim()
android {
applicationVariants.all { variant ->
variant.outputs.all { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.apk')) {
//这里修改apk文件名
def fileName = outputFile.name.replace("app", "test-${gitSha}")
outputFileName = fileName;
}
}
}
}
网友评论