首页 文章

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

提问于
浏览
25

当我使用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中创建这样的文件名?

2 回答

  • 35

    Update: Please check Anrimian's answer below which is much simpler and shorter.

    试试这个:

    gradle.properties

    applicationName = MyApp
    

    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)
     }
    }
    

    Reference: https://stackoverflow.com/a/30332234/206292 https://stackoverflow.com/a/27104634/206292

  • 79

    这可能是最短的方式:

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

    buildType:像这样

    buildTypes {
        debug {
            ...
            versionNameSuffix "-T"
        }
        release {
            ...
            versionNameSuffix "-R"
        }
    }
    

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

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

    defaultConfig {
        ...
        archivesBaseName = "$applicationId-v$versionCode($versionName)"
    }
    

相关问题