A consider myself a decently experienced Android developer. But I stumbled when recently a friend, an iOS-developer-turning-into-Android-developer, asked me if there's a way to automate the boring task of updating the version code before a new cut.
I mean I knew that Gradle, the build system Android Studio uses by default, uses a Groovy-based DSL that is quite powerful. So this should be possible.
I went for a search online, but I had in mind that whatever I found should satisfy the following:
- automatic version code every time I run / release
- no dependencies on external files
- (optional) human-readable version name
Auto-increment version code (literally)
I found that is possible to add a new Gradle task, in the correct order, that will do exactly what I manually do: increase the build version code.
As you can see, using regex you can find the part where
versionCode is defined, increase the version code, and replace the contents of the file.
Although this works, it's quite brittle. Any future change to the way
versionCode is defined will break this. If you decide to change the
versionName as well, this can become more complicated (especially if you have multiple Build Variants).
Date-derived version code
Another approach I found is creating a new version code based on date/time.
The highest version code you can have is 2100000000. You can print the date in
yyMMddHHmm but this only allows the latest year to be 2021, which is quite limiting. Going with
yyMMddHH, on the other hand, allows a different version every hour until 2099. I don't plan to release my apps more often than hourly, or after 2099.
offset is there in the unlikely event that I do want to create another
versionCode in the same hour.
Then, in your
defaultConfig section, you need to replace the static
versionCode with this dynamic one.
I find this approach less brittle and less invasive. Also, this works well if you are defining Build Variants and using the
versionNameSuffix to distinguish between them.
Hopefully, my simple approach in automating versioning for Android might be useful in your projects :)