Is it possible to set the code and name of the Android version using the Gradle task?

I am trying to automate the build process on the CI that I am working with. I can call curland assign it some variables, such as version code and names. Then CI (in my case, Bitrise CI) catches it and starts the release build. However, before that, I want to set the version code and version name based on what was transferred curlto the file build.gradle, and then the build process starts.

So, I think I can write a plugin / task that gets the code / version name from the command line and then inserts it into the file build.gradle. Type command ./gradlew setVersion 1 1.0.

Thirdly, by running this command from a script that I will write, I can run this task, and everyone can find the release build using curl. Pretty interesting :)

I can write a task similar to the following code and put it in my main file build.gradle.

task setVersion << {
    println versionCode
    println versionName
}

and pass it some parameters via the command line:

./gradlew -PversionCode=483 -PversionName=v4.0.3 setVersion

This is my conclusion:

:setVersion
483
v4.0.3

BUILD SUCCESSFUL

Total time: 6.346 secs

So far so good. I have a question, how to install it in a file build.gradle?

+5
source share
1 answer

You can create methods for updating the version of Code and versionName from the command line:

def getMyVersionCode = { ->
    def code = project.hasProperty('versionCode') ? versionCode.toInteger() : -1
    println "VersionCode is set to $code"
    return code
}

def getMyVersionName = { ->
    def name = project.hasProperty('versionName') ? versionName : "1.0"
    println "VersionName is set to $name"
    return name
}

Then in the android block:

defaultConfig {
        applicationId "your.app.id"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode getMyVersionCode()
        versionName getMyVersionName()

        archivesBaseName = "YourApp-${android.defaultConfig.versionName}"
    }

Then you can just call any task:

./gradlew assembleDebug -PversionCode=483 -PversionName=4.0.3

: https://robertomurray.co.uk/blog/2013/gradle-android-inject-version-code-from-command-line-parameter/

+14

All Articles