Gradle

How To Auto Increment Build Number Using Gradle

Auto Increment Build Number

 

What Is A Build Number?

A build number uniquely identifies unreleased or released application and we can find out build number in version name. Most commonly used Version Name format is MAJOR.MINOR.REVISION.BUILDNUMBER.  The change in the respective places signifies type of the release, i.e, major, minor or revision. Where build number is total number of build taken so far during the development of the application. (Sometimes use datetime as build number so developer can find out the build date)

screen_buildnum_ws

 

Why Auto Increment Build Number ?

It is not practical to increment build number manually on each build because we build APK many times during the development. It is good to automate the process of incrementing the build number but Android Studio IDE does not support this feature. So we have to change the build logic for this using a small Groovy method.

Things To Do

  • Create a file called version.properties file with value 0 (Zero) as initial value.
  • Read value from file.
  • Append value to versionName attribute.
  • Increment and overwrite content of the file.

Step 1: Store Build Number In A file

Create a property file named version.properties in the root of the module directory and write VERSION_BUILD=0 as content. Where VERSION_BUILD is a variable that holds the number of last build. On each release it will get incremented.

version properties file content

Step 2 : Locate defaultConfig Tag in build.gradle

Open build.gradle file inside main module(app) directory. There is a tag named defaultConfig , the content of this tag may look like this,

 defaultConfig {
            minSdkVersion 16
            targetSdkVersion 21
            versionCode 1
            versionName "1.0.0"
        }

Our aim is to append build number to versionName. So we have to write some logic before defaultConfig tag. Please see the code below.

Step 3: Write Auto Increment Script

Open build.gradle file in the main module(app) directory and write the following code inside android { ... } tag.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.2'

    def versionPropsFile = file('version.properties')
    def versionBuild

    /*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()
    } 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 = {

        if (versionPropsFile.canRead()) {
            def Properties versionProps = new Properties()
            versionProps.load(new FileInputStream(versionPropsFile))
            versionBuild = versionProps['VERSION_BUILD'].toInteger() + 1
            versionProps['VERSION_BUILD'] = versionBuild.toString()
            versionProps.store(versionPropsFile.newWriter(), null)
        } else {
            throw new FileNotFoundException("Could not read version.properties!")
        }
    }


    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 21
        versionCode 1
        versionName "1.0.0." + versionBuild
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    // Hook to check if the release/debug task is among the tasks to be executed.
    //Let's make use of it
    gradle.taskGraph.whenReady {taskGraph ->
        if (taskGraph.hasTask(assembleDebug)) {  /* when run debug task */
            autoIncrementBuildNumber()
        } else if (taskGraph.hasTask(assembleRelease)) { /* when run release task */
            autoIncrementBuildNumber()
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:25.3.1'
}

Explanation Of The Above Code

The above written code simply read the version.properties file and get integer value (1,2,3…) stored in the VERSION_BUILD variable. Increment the variable by 1 and assign it to a versionBuild variable and append to the value of versionName property. After that store the new incremented value back to version.properties file. That’s it.

Screenshot From IDE

gradle_auto_increment_varia

Run The Project

You can see the build number when you open the application information page of the app. It will look like this,

screen_build_number_half

The last part is now ‘0’ because it is the first run. This value will be keep incrementing on each build on wards.

run_auto_increment_half

Please post your questions on this topic through comment section if you have any doubts.

Thanks & Good luck!

About author

Geethu is a teacher by profession, but she likes to research new things and is also interested in writing. Devdeeds is her blog, where she writes all the blog posts related to technology, gadgets, mobile apps, games, and related content.

Leave a Reply

Your email address will not be published. Required fields are marked *