我最近升级到 Android Studio 2.3,现在我打算像往常一样使用 Build/Generate signed APK...
为我现有的应用之一生成一个签名的 APK。之前我总是得到一个名为 MyApp-1.0.apk
的文件(其中 1.0
是版本名称),但现在我得到了 MyApp-1.0-unaligned.apk
。
我注意到有一些新的选项可以选择 V1 (Jar signature)
和/或 V2 (Full APK Signature
)。我选择了两者,如 recommended in the documentation。然而,文档确实说明了这一点
Caution: If you sign your app using APK Signature Scheme v2 and make further changes to the app, the app's signature is invalidated. For this reason, use tools such as zipalign before signing your app using APK Signature Scheme v2, not after.
在我的 build.gradle
我有
buildTypes {
debug{
// Enable/disable ProGuard for debug build
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
zipAlignEnabled true
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-project.txt'
zipAlignEnabled true
}
}
我见过一些人在使用 Android gradle 构建工具的 alpha 版本时遇到过类似的问题,但我使用的是 2.3.0
:
classpath 'com.android.tools.build:gradle:2.3.0'
那么如何在签名之前使 APK 生成过程对我的 APK 进行 zipalign?
最佳答案
问题是由外部 gradle 脚本管理生成的 APK 的文件名引起的。我完全忘记了那个脚本,现在它开始无法检查 APK 是否经过压缩对齐,因为 Google 引入了 v2 签名。
我将脚本包含在我的 build.gradle
中,如下所示
apply from: '../../export_signed_apk.gradle'
脚本本身是这样的
android.applicationVariants.all {
variant -> def appName
//Check if an applicationName property is supplied; if not use the name of the parent project.
if (project.hasProperty("applicationName")) {
appName = applicationName
} else {
appName = parent.name
}
variant.outputs.each {
output -> def newApkName
//If there's no ZipAlign task it means that our artifact will be unaligned and we need to mark it as such.
if (output.zipAlign) {
newApkName = "${appName}-${variant.versionName}.apk"
} else {
newApkName = "${appName}-${variant.versionName}-unaligned.apk"
}
output.outputFile = new File(output.outputFile.parent, newApkName)
}
}
output.zipAlign
似乎在应用 V2 签名后失败了,因此它会返回 myApp-1.0-unaligned
,即使已签名的 APK 确实是 zipaligned。
我只是删除了 IF 语句,并保留
newApkName = "${appName}-${variant.versionName}.apk"
关于Android Studio 2.3 正在生成未对齐的签名 APK 而不是 zipaligned?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43212162/