我正在使用Gradle来编译我的Android项目:
buildTypes {
release {
signingConfig signingConfigs.release
applicationVariants.all { variant ->
def file = variant.outputFile
def fileName = file.name
fileName = fileName.replace(".apk", "-renamed".apk")
variant.outputFile = new File(file.parent, fileName)
}
}
}
并非所有输出文件都已重命名,它始终会跳过1个文件。为什么呢?
myapp-debug-unaligned-renamed.apk <-renamed, OK!
myapp-release.apk <-NOT renamed, WRONG!
myapp-release-unaligned-renamed.apk <-renamed, OK!
答案 0 :(得分:16)
我使用此代码解决了:
buildTypes {
release {
signingConfig signingConfigs.release
}
applicationVariants.all { variant ->
def apk = variant.packageApplication.outputFile;
def newName = apk.name.replace(".apk", "-renamed.apk");
variant.packageApplication.outputFile = new File(apk.parentFile, newName);
if (variant.zipAlign) {
variant.zipAlign.outputFile = new File(apk.parentFile, newName.replace("-unaligned", ""));
}
}
}
块applicationVariants.all {...}
现在位于release {...}
块之外。
我认为variant.zipAlign.outputFile
会有所不同。
答案 1 :(得分:4)
使用build.gradle配置时应该有3个输出APK文件:debug unsigned unaligned,release signed aligned和release signed unaligned。 applicationVariant
处理输出文件有两个变量: outputFile 和 packageApplication.outputFile ,前者用于zipalign,后者用于一般情况
因此,重命名所有文件的正确方法如下:
android.applicationVariants.all { variant ->
if (variant.zipAlign) {
def oldFile = variant.outputFile;
def newFile = oldFile.name.replace(".apk", "-renamed.apk")
variant.outputFile = new File(oldFile.parent, newFile)
}
def oldFile = variant.packageApplication.outputFile;
def newFile = oldFile.name.replace(".apk", "-renamed.apk")
variant.packageApplication.outputFile = new File(oldFile.parent, newFile)
}
答案 2 :(得分:-1)
我通过删除你的一行来简化它,但基本上你需要改变它:
android {
buildTypes {
...
}
applicationVariants.all { variant ->
def file = variant.outputFile
def fileName = file.name.replace(".apk", "-renamed".apk")
variant.outputFile = new File(file.parent, fileName)
}
}