Search code examples
androidbuildandroid-manifestgradleauto-increment

How to autoincrement versionCode in Android Gradle


I'm experimenting with new Android build system based on Gradle and I'm thinking, what is the best way to autoincrease versionCode with it. I am thinking about two options

  1. create versionCode file, read number from it, increase it and write it back to the file
  2. parse AndroidManifest.xml, read versionCode from it, increase it and write it back to the AndroidManifest.xml

Is there any more simple or suitable solution?

Has anyone used one of mentiod options and could share it with me?


Solution

  • I have decided for second option - to parse AndroidManifest.xml. Here is working snippet.

    task('increaseVersionCode') << {
        def manifestFile = file("AndroidManifest.xml")
        def pattern = Pattern.compile("versionCode=\"(\\d+)\"")
        def manifestText = manifestFile.getText()
        def matcher = pattern.matcher(manifestText)
        matcher.find()
        def versionCode = Integer.parseInt(matcher.group(1))
        def manifestContent = matcher.replaceAll("versionCode=\"" + ++versionCode + "\"")
        manifestFile.write(manifestContent)
    }
    
    tasks.whenTaskAdded { task ->
        if (task.name == 'generateReleaseBuildConfig') {
            task.dependsOn 'increaseVersionCode'
        }
    }
    

    versionCode is released for release builds in this case. To increase it for debug builds change task.name equation in task.whenTaskAdded callback.