Auto-updating an Android Project’s versionCode
This is a quick tip I’ve enjoyed using over the past few years in some of the Android apps I’ve worked on. Instead of having to manually update the “versionCode” of your build.gradle script, you can easily automate it by adding a single line of code. This technique is especially useful if you have a continuous integration (CI) job constantly pushing updates out to Google Play for your testers to play around with. Automation is always better, right?
Anyway, to get started go ahead and open your “app/build.gradle” file and add the following line of code to the start of the file:
def buildVersionCode = Integer.parseInt(new Date().format("yyMMddHH"))
Scroll down a bit in the file until you find your existing “versionCode” setting. It may look something like this:
Simply change it to:
Now, the next time you build, your versionCode will be based on today’s date and time and will always increment between builds.
If you don’t see a “versionCode” in your build.gradle file, check to see if it’s defined in your AndroidManifest.xml file. If you see it there, just remove it and add both “versionCode” and “versionName” to your build.gradle file under the android > defaultConfig section. It should be at the same level as your applicationId.
Do you use a different technique? Let me know in the comments below or by reaching out to me on Twitter!