[Android打包]Android Studio打包重命名

广而告之,打开支付宝首页搜索“9191078”,即可领红包。每天都可以领哦~

(界面下面的余额宝红包更大,但使用的时候记得使用余额宝支付才能用哦!)


前言

我们使用Android Studio打包的时候,一般默认命名为app-debug.apk或者app-release.apk。但有时候有很多种渠道,或者要标记安装包的版本等信息,需要对安装包重命名。手动修改的时代已经过去,费时费力。我们来看下,如何能够使用代码自动重新命名安装包。

步骤

重命名的名字格式为:我的命名_V1.1.0_C1_20180625.apk

只需要在app的build.gradle的android内写入如下代码:

applicationVariants.all { variant ->
        variant.outputs.each { output ->
          def outputFile = output.outputFile
          if (outputFile != null && outputFile.name.endsWith('.apk')) {
            def fileName = outputFile.name.replace(outputFile.name,
                "我的命名" + "_V${defaultConfig.versionName}_C${defaultConfig.versionCode}_${getDate()}.apk")
            output.outputFile = new File(outputFile.parent, fileName)
          }
        }

但是有的小伙伴打包的时候会报错:

Error:(34, 0) Cannot set the value of read-only property 'outputFile' for ApkVariantOutputImpl_Decorated{apkData=Main{type=MAIN, fullName=debug, filters=[]}} of type com.android.build.gradle.internal.api.ApkVariantOutputImpl. <a href="openFile:C:\projects

原因:Android Plugin3.0建议使用:

Use all() instead of each()
Use outputFileName instead of output.outputFile if you change only file name (that is your case)

所以我们这样写:

applicationVariants.all { variant ->
    variant.outputs.all {
      def fileName = "我的命名" + "_V${defaultConfig.versionName}_C${defaultConfig.versionCode}_${getDate()}_" +
          variant.name +
          ".apk"
      outputFileName = fileName
    }
  }

结语

有什么问题我会继续更新的。希望能帮助大家。


个人微信公众号:摩羯座程序媛的日常 (dreamflower_hannah)

CSDN:https://blog.csdn.net/wj9966

简书:https://www.jianshu.com/u/dad160fe192d  (梦里花开)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章