如何使用这种格式的gradle更改apk名称?

S.J*_*Lim 36 android gradle

当我使用gradle构建应用程序时,我想将"app-release.apk"文件名更改为以下内容.

[format]
(appname of package name)_V(version code)_(yyMMdd)_(R|T)

[explain]
(appname of package name) : example) com.example.myApp -> myApp
(version code) : build version code 2.2.3 -> 223
(yyMMdd) : build date 2015.11.18 -> 151118  
(R|T) : if app is release, "R" but debug is "T".

如果我在发布中生成apk文件,结果是:myApp_V223_151118_R.apk.

如何在gradle中创建这样的文件名?

Anr*_*ian 96

这可能是最短的方式:

defaultConfig {
    ...
    applicationId "com.blahblah.example"
    versionCode 1
    versionName "1.0"
    setProperty("archivesBaseName", applicationId + "-v" + versionCode + "(" + versionName + ")")
}
Run Code Online (Sandbox Code Playgroud)

buildType:像这样

buildTypes {
    debug {
        ...
        versionNameSuffix "-T"
    }
    release {
        ...
        versionNameSuffix "-R"
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,默认情况下,Android Studio会按版本类型名称添加versionNameSuffix,因此您可能不需要此版本.

UPD.在Android Studio的新版本中,您可以写得更短(感谢szx评论):

defaultConfig {
    ...
    archivesBaseName = "$applicationId-v$versionCode($versionName)"
}
Run Code Online (Sandbox Code Playgroud)

  • 在最近的gradle版本中,您可以使用`archivesBaseName ="$ applicationId-v $ versionCode($ versionName)"`(在我看来读得更好) (5认同)
  • 这是他们中最好的答案 (2认同)

Kri*_*raj 38

更新:请在下面查看Anrimian的答案,该答案更简单,更短.

试试这个:

gradle.properties

applicationName = MyApp
Run Code Online (Sandbox Code Playgroud)

的build.gradle

android {
  ...
  defaultConfig {
     versionCode 111
     ...
  }
  buildTypes {
     release {
         ...
         applicationVariants.all { variant ->
             renameAPK(variant, defaultConfig, 'R')
         }
     }
     debug {
         ...
         applicationVariants.all { variant ->
             renameAPK(variant, defaultConfig, 'T')
         }
     }
  }
}
def renameAPK(variant, defaultConfig, buildType) {
 variant.outputs.each { output ->
     def formattedDate = new Date().format('yyMMdd')

     def file = output.packageApplication.outputFile
     def fileName = applicationName + "_V" + defaultConfig.versionCode + "_" + formattedDate + "_" + buildType + ".apk"
     output.packageApplication.outputFile = new File(file.parent, fileName)
 }
}
Run Code Online (Sandbox Code Playgroud)

参考: https ://stackoverflow.com/a/30332234/206292 /sf/answers/1897324411/

  • applicationVariants.all不应嵌套在每个变体中:debug {} release {} applicationVariants.all {variant - > renameAPK(variant,defaultConfig,variant.name)} (4认同)

Zum*_*med 9

2019 - How to change APK name For Gradle 3.3, 3.4, 3.5 and above

android {
   ......
   applicationVariants.all { variant ->
       variant.outputs.all {
           def flavor = variant.name
           def versionName = variant.versionName
           outputFileName = "prefix_${flavor}_${versionName}.apk"
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

The result would be like this,

prefix_release_1.0.1.apk

  • 可能是也可能不是这个问题的答案,但它回答了我的另一个问题。谢谢。 (3认同)
  • 感谢您的回答。它挽救了我的一天 (2认同)