简体   繁体   中英

Android: Auto Increment version code only on Release BuildType in Gradle

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM