4

I have read this topic: Autoincrement VersionCode with gradle extra properties

But it seems to increase the versionCode on every build (builds up a lot if you run debug version often).

Is there a way to tweak the answer so that VersionCode only increases when I build a release signed version in Android Studio?

Community
  • 1
  • 1
Stephane Maarek
  • 5,202
  • 9
  • 46
  • 87
  • Did you have a look [here](http://stackoverflow.com/questions/21405457/autoincrement-versioncode-with-gradle-extra-properties/28043555#28043555)? – carvaq Jan 20 '15 at 10:56
  • Check this: http://stackoverflow.com/a/21951328 – Yazon2006 Dec 05 '16 at 10:06
  • Or this: https://stackoverflow.com/questions/23516090/android-studio-gradle-version-increment/46467575#46467575 – sunnyday Sep 28 '17 at 11:06

1 Answers1

4

For this solution is necessary a file version.properties.

in build.gradle:

def getVersionCode() {
    def propertiesFile = file('version.properties')

    if (!propertiesFile.canRead()) {
        throw new GradleException("Could not read " + propertiesFile.name)
    }

    Properties properties = new Properties()
    properties.load(new FileInputStream(propertiesFile))

    def code = properties['VERSION_CODE_PROD'].toInteger()

    gradle.taskGraph.whenReady { tasksGraph ->
        List<Task> tasks = tasksGraph.getAllTasks()

        for (Task task : tasks) {
            if (task.name.contains("Production")) {
                code = code + 1
                properties['VERSION_CODE_PROD'] = code.toString()
                properties.store(propertiesFile.newWriter(), null)
                break
            }
        }
    }

    return code
}

android {

    def code = getVersionCode()

    defaultConfig {
        ...
        versionCode code
        ...
    }
}