使用gradle更新Android应用程序版本(存储在build.gradle中)

时间:2015-04-02 12:20:22

标签: android android-studio gradle

在gradle中执行某项任务时,可以更新Android或库版本versionCodeversionName吗? versionCode / Name放在我的android / build.gradle

我正在寻找一个完整的gradle脚本,而不是shell脚本。

它与How to autoincrement versionCode in Android Gradle不同,因为versionCode和versioName存储在build.gradle中而不是清单中

1 个答案:

答案 0 :(得分:0)

在你想要更新的build.gradle中,我已经更改了一个脚本来编辑当前的build.gradle并增加了versionCode和versionName。

将此任务添加到您的gradle:

task incrementVersionCode << {
    println("Incrementing Version Code...")
    def manifestFile = file("build.gradle")
    def patternVersionCode = Pattern.compile("versionCode (\\d+)")
    def manifestText = manifestFile.getText()
    def matcherVersionCode = patternVersionCode.matcher(manifestText)
    matcherVersionCode.find()
    def mVersionCode = Integer.parseInt(matcherVersionCode.group(1))
    def mNextVersionCode = mVersionCode + 1
    def manifestContent = matcherVersionCode.replaceAll("versionCode " + mNextVersionCode)
    println("> Set versionCode(" + mVersionCode + ") to " + mNextVersionCode);
    manifestFile.write(manifestContent)
}

task incrementVersionName << {
    println("Incrementing Version Name...")
    def manifestFile = file("build.gradle")
    def patternVersionNumber = Pattern.compile("versionName \"(\\d+)\\.(\\d+)\\.(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcherVersionNumber = patternVersionNumber.matcher(manifestText)
    matcherVersionNumber.find()
    def majorVersion = Integer.parseInt(matcherVersionNumber.group(1))
    def minorVersion = Integer.parseInt(matcherVersionNumber.group(2))
    def pointVersion = Integer.parseInt(matcherVersionNumber.group(3))
    def mVersionName = majorVersion + "." + minorVersion + "." + pointVersion
    def mNextVersionName = majorVersion + "." + minorVersion + "." + (pointVersion + 1)
    def manifestContent = matcherVersionNumber.replaceAll("versionName \"" + mNextVersionName + "\"")
    println("> Set versionName(" + mVersionName + ") to " + mNextVersionName);
    manifestFile.write(manifestContent)
}

<强>用法

如果您想在运行./gradlew bintrayUpload时更新版本(例如,mut,它可以是您想要的任务),请添加:

bintrayUpload.dependsOn incrementVersionCode
bintrayUpload.dependsOn incrementVersionName