user3017844
user3017844

Reputation: 58

gradle script doesn't work while app bundle building

I have some code in app-gradle file to auto increment build version number.
It works fine when i'am building single apk file.
But it doesn't increase anything when i start to build App-Bundle.
I have some misunderstanding where is the problem. (there also 'version.properties' file in 'app\src' folder, with single line in it - VERSION_BUILD=13).

apply plugin: 'com.android.application'

android {

    compileSdkVersion 28


    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!")
        }
    }

    // Hook to check if the release/debug task is among the tasks to be executed.
    gradle.taskGraph.whenReady {taskGraph ->
        if (taskGraph.hasTask(assembleDebug)) {
            //autoIncrementBuildNumber()
        } else if (taskGraph.hasTask(assembleRelease)) {
            autoIncrementBuildNumber()
        }
    }


    defaultConfig {
        applicationId "com.example.one"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode versionBuild
        versionName "1.0." + versionBuild
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

Upvotes: 2

Views: 719

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363597

To build the app bundle with gradle you use the command bundle<Variant> instead of assemble<Variant>.

It means that in your code you have to check (or to add) also the task bundleRelease

else if (taskGraph.hasTask(bundleRelease)) {
            autoIncrementBuildNumber()

Upvotes: 4

Related Questions