android gradle 修改生成的apk的名字

Android Studio打包应用默认生成的apk名称是:app-release.apk 、app-debug.apk
如果我们要让生成的apk名跟我们版本包名、渠道号有联系的话,那我们就要自定义生成的apk名了
需要在build.gradle(Module:app)文件下android{ }中添加:
android.applicationVariants.all {
        variant ->
            variant.outputs.each { output ->

                def outputFile = output.outputFile

                if (outputFile != null && outputFile.name.endsWith('.apk')) {

                    def name = "qq_v${defaultConfig.versionName}_${variant.productFlavors[0].name}_${buildType.name}.apk"

                    output.outputFile = new File(outputFile.parent, name)
                }

            }
    }
//多渠道
 productFlavors {
        tencent{
        }
        vivo{
        }
        oppo{
        }
    }

修改名字的地方

def name = "xxx_${defaultConfig.versionName}_${variant.productFlavors[0].name}_${buildType.name}.apk"
xxx:为你自己的工程名,自己起的标识- 比如 wx、qq、taobao
defaultConfig.versionName:版本号
variant.productFlavors[0].name:渠道标识
buildType.name:build方式release/debug
//这么写也可以
def name= "qq"+"_"+"v"+defaultConfig.versionName+"_"+variant.productFlavors[0].name+"_"+buildType.name+".apk"

然后使用命令打包

./gradlew assemble –会同时打debug和release的包
使用如上命令测试出包如图:

《android gradle 修改生成的apk的名字》

./gradlew assembleRelease –只打release的包

AndroidStudio升级到3.0后这种方式会有问题

Cannot set the value of read-only property 'outputFile' for ApkVariantOutputImpl_Decorated{apkData=Main{type=MAIN, fullName=release, filters=[]}} of type com.android.build.gradle.internal.api.ApkVariantOutputImpl. Open File

1.需要修改 each() 和 outputFile() 方法为 all()

2.outputFileName

 applicationVariants.all { variant ->
        if (variant.buildType.name == 'release') {
            variant.outputs.all {
                def apkName = "qq_v${defaultConfig.versionName}_${variant.productFlavors[0].name}_${buildType.name}"
                outputFileName = apkName + ".apk"
            }
        }
    }
    原文作者:芒果味的你呀
    原文地址: https://www.jianshu.com/p/7f69ce981e6f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞