Changing APK/AAB version from the command line

Changing APK/AAB version from the command line
Photo by Gabriel Heinzer / Unsplash

Earlier today I was looking into automatically building an APK/AAB artifact for one of the projects I am working on, using GitHub Actions. After the basic setup, I had to run the assemble command and it generated the artifact then I upload that to the action, or I can publish it somewhere I want. Pretty straightforward.

But one issue is, I had to manually update the version code and version name every time I had to make a new release. While it's not that big of work, I instead let a computer take care of versioning than me.

On Simple, we use Bitrise which provides us with a step that sets the version when running the workflow. So, I wanted to do something similar to that.  I wanted to have a step that generates a version based on the current date and build/run.

So, one of the immediate approaches that came to mind for something like that was using gradle.properties. I can define a custom property and then read that in my build file when setting the version code and name. That would look something like this

appVersionCode=1
appVersionName=0.1
gradle.properties
versionCode = providers.gradleProperty("appVersionCode").get()
versionName = providers.gradleProperty("appVersionName").get()
build.gradle.kts

...and then I just have to pass the values I generated using properties in the Gradle command

./gradlew :app:assembleDebug \
-PappVersionCode=1 \
-PappVersionName=2022-12-24-1

That's it, this would generate the artifact with the version code and name I passed.

💡
Info: The next approach only works on AGP < 7.3.0. It looks like they removed the android.injected.version properties in newer AGP versions.

But I do want to see if there was a native way of doing this. After a bit of Googling and command clicking, I found that build tools have Gradle property that does help with this.

AndroidProject.java

That's it, with these properties I didn't have to make any changes to the project build files and instead just had to pass the version information in the Gradle command

// version code and name are generated and are passed to this command

./gradlew :app:assembleDebug \
-Pandroid.injected.version.code=1 \
-Pandroid.injected.version.name=2022-12-24-1

This was a bit of a small thing I learned today, so wanted to share it. Hopefully, this will be useful for someone else as well :D