android - 使用 Gradle 更改 apk 名称

标签 android gradle apk android-gradle-plugin

我有一个使用 Gradle 进行构建过程的 Android 项目。现在我想添加两个额外的构建类型 staging 和 production,所以我的 build.gradle 包含:

android {
    buildTypes {
        release {
            runProguard false
            proguardFile getDefaultProguardFile('proguard-android.txt')
        }

        staging {
            signingConfig signingConfigs.staging

            applicationVariants.all { variant ->
                appendVersionNameVersionCode(variant, defaultConfig)
            }
        }

        production {
            signingConfig signingConfigs.production
        }
    }
}

我的 appndVersionNameVersionCode 看起来像:

def appendVersionNameVersionCode(variant, defaultConfig) {
    if(variant.zipAlign) {
        def file = variant.outputFile
        def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk")
        variant.outputFile = new File(file.parent, fileName)
    }

    def file = variant.packageApplication.outputFile
    def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk")
    variant.packageApplication.outputFile = new File(file.parent, fileName)
}

如果我执行任务 assembleStaging 然后我会得到我的 apk 的正确名称,但是当我执行 assembleProduction 然后我会得到我的 apk 的更改名称(例如在暂存情况下) .例如:

MyApp-defaultFlavor-production-9.9.9-999.apk
MyApp-defaultFlavor-production-9.9.9-999.apk

看起来在生产构建类型中执行了 appendVersionNameVersionCode。如何避免?

最佳答案

正如 CommonsWare 在他的评论中所写,您应该只为暂存变体调用 appendVersionNameVersionCode。您可以轻松做到这一点,只需稍微修改您的 appendVersionNameVersionCode 方法,例如:

def appendVersionNameVersionCode(variant, defaultConfig) {
    //check if staging variant
    if(variant.name == android.buildTypes.staging.name){
        if(variant.zipAlign) {
            def file = variant.outputFile
            def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk")
            variant.outputFile = new File(file.parent, fileName)
        }

    def file = variant.packageApplication.outputFile
    def fileName = file.name.replace(".apk", "-" + defaultConfig.versionName + "-" + defaultConfig.versionCode + ".apk")
    variant.packageApplication.outputFile = new File(file.parent, fileName)
    }
}

关于android - 使用 Gradle 更改 apk 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22126299/

相关文章:

android - 导入外部jar和Gradle错误

android - 仅构建默认值(无口味/变体)

android - 从Flutter项目构建APK时出错

android - 如何在 Google Play 控制台中限制特定 Android 版本的应用程序

java - 方法 : The local variable editText may not have been initialized 中带有 EditText 的 AlertDialog

android - list 文件中声明的电池广播接收器不起作用?

android-studio - React-native (Signed) release apk 在设备中不断崩溃

android - 将项目从 Github 导入到 Android Studio 时显示错误

gradle - 如何在Gradle脚本中不使用任务删除Java文件?

android - 找不到 Library.apk!