2015-11-18 21 views
11

我想通過使用gradle構建應用程序時將「app-release.apk」文件名更改爲喜歡以下內容。如何使用這種格式的gradle更改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". 

如果我在release中生成一個apk文件,結果是:myApp_V223_151118_R.apk。

如何在gradle中創建一個像這樣的文件名?

回答

28

更新:請檢查下面的Anrimian's answer更簡單更簡單。

試試這個:

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

參考: https://stackoverflow.com/a/30332234/206292 https://stackoverflow.com/a/27104634/206292

+0

當我這樣做時,我得到:app-development-release.apk,app-live-release.apk。它爲什麼說「應用程序」而不是我的應用程序名稱? – Subby

+1

@Subby確保你已經在gradle.properties中設置了你的applicationName。 – Krishnaraj

+4

applicationVariants.all不應該被嵌套在每個變體: 調試{} 發佈{} applicationVariants.all {變種 - > renameAPK(變種,defaultConfig,variant.name) } – wolfprogrammer

30

這可能是最短的方式:

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通過構建類型名稱默認情況下,所以你可能不需要這個。

+0

這應該是公認的答案 – ElliotM

+0

這是他們所有人的最佳答案 –