Skip to content

Instantly share code, notes, and snippets.

@rdiaz82
Last active December 11, 2017 12:55
Show Gist options
  • Save rdiaz82/4fbbd41f81fbd2e7dd2872100721a918 to your computer and use it in GitHub Desktop.
Save rdiaz82/4fbbd41f81fbd2e7dd2872100721a918 to your computer and use it in GitHub Desktop.
Gist with common Android tasks!

Autoincrement Build Version in Gradle

The original source is the following, http://devdeeds.com/auto-increment-build-number-using-gradle-in-android/ I have added some minor changes

Create a file with the build version at the module level version.properties:

VERSION_BUILD=1
VERSION_BUILD_CRASHLYTICS=1

Inside the build gradle do something like this:

versionName "1.0."

 /*Setting default value for versionBuild which is the last incremented value stored in the file */
    if (versionPropsFile.canRead()) {
        def Properties versionProps = new Properties()
        versionProps.load(new FileInputStream(versionPropsFile))
        versionBuild = versionProps['VERSION_BUILD'].toInteger()
        versionBuildCrashlytics = versionProps['VERSION_BUILD_CRASHLYTICS'].toInteger()
    } else {
        throw new FileNotFoundException("Could not read version.properties!")
    }
    
/*Wrapping inside a method avoids auto incrementing on every gradle task run. Now it runs only when we build apk*/
    ext.autoIncrementBuildNumber = { envVar ->
            if (versionPropsFile.canRead()) {
                Properties versionProps = new Properties()
                versionProps.load(new FileInputStream(versionPropsFile))
                versionBuild = versionProps[envVar].toInteger() + 1
                versionProps[envVar] = versionBuild.toString()
                versionProps.store(versionPropsFile.newWriter(), null)
            } else {
                throw new FileNotFoundException("Could not read version.properties!")
            }
    }

    gradle.taskGraph.whenReady {taskGraph ->
        if (taskGraph.hasTask(assembleReleaseCrashlytics)) {  /* when run debug task */
            autoIncrementBuildNumber('VERSION_BUILD_CRASHLYTICS')
        } else if (taskGraph.hasTask(assembleRelease)) { /* when run release task */
            autoIncrementBuildNumber('VERSION_BUILD')
        }
    }
    
    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            if (variant.name.contains('Crashlytics'))
                outputFileName = "${variant.name}-${variant.versionName}${versionBuildCrashlytics}.apk"
            else
                outputFileName = "${variant.name}-${variant.versionName}${versionBuild}.apk"
        }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment