星期日, 八月 03, 2014

如何在Android Studio beta 版本里加入Build versionNumber的脚本。

利用AndroidManifest.xml里的android:versionCode"整数",
android:versionName为字符串,格式为"0.0.1"的格式。

将一下代码复制到build.gradle里,最后空白的地方,sync之后即可:
这是在build project的时候,即更新AndroidManifest.xml里的
这两个字段

task('increaseVersionCode') << {
    def manifestFile = file(android.sourceSets.main.manifest.srcFile)
    def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
    def manifestText = manifestFile.getText()
    def matcher = pattern.matcher(manifestText)
    matcher.find()
    def versionCode = Integer.parseInt(matcher.group(1))
    versionCode= versionCode+1
    def manifestContent = matcher.replaceAll("versionCode=\"" + versionCode + "\"")
    manifestFile.write(manifestContent)
    println  "versionCode is:"+versionCode

}

task('incrementVersionName') << {
    def manifestFile = file(android.sourceSets.main.manifest.srcFile)
    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 buildVersion = Integer.parseInt(matcherVersionNumber.group(3))
    def mNextVersionName = majorVersion + "." + minorVersion + "." +  + (buildVersion + 1)
    def manifestContent = matcherVersionNumber.replaceAll("versionName=\"" + mNextVersionName + "\"")
    println  "build number is:"+mNextVersionName
    manifestFile.write(manifestContent)
}

tasks.whenTaskAdded { task ->
    if (task.name == 'generateReleaseBuildConfig' || task.name == 'generateDebugBuildConfig') {
        task.dependsOn 'increaseVersionCode'
        task.dependsOn 'incrementVersionName'
    }
}