[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  (夢裏花開)


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