Android Studio 2.3 正在生成未对齐的签名 APK 而不是 zipaligned?

标签 android android-studio apk android-studio-2.3 zipalign

我最近升级到 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/

相关文章:

设备上的 Android 错误 : Failed to install *. apk *:超时

android - 如何用Delphi XE5制作安卓动态壁纸?

android - 错误 :Failed to complete Gradle execution. 原因:未知的命令行选项 '-X'

安卓工作室 : release apk signing process

java - 如何使用JPMML-Android实现PMML机器学习模型?

c# - 为什么我的 OpenGL ES 应用程序在 glDrawElements 上崩溃?

java - 如何在同一 Activity 中从一个布局切换回父布局

android-studio - Android Studio 升级到北极狐后出现奇怪的代码子窗口(2020.3.1)

Android 支持库大大增加了 APK 的大小

android - 将 Maven Artifact 的不同包装附加到部署?