Tuesday, 11 October 2011

Android: Getting the version of your App

(AKA how to get the version of the app from the manifest file)

I wrote previously here how to add logging to your app and one of the things you most certainly want to put in your log is the version of your software.
In fact I got a ton of messages asking how to do that, reason why I'm writing this quick and short post :)

There are two version fields that we should get: version name and version code.
Version name is however you want to call the version of your app and version code is an integer number that basically says "this version is new that the other one".
Both fields are attributes if the same name in the manifest file. You need to set it manually so look for android:versionCode and android:versionName.
Programmatically reading versionName and versionCode.

The attributes we set manually in the manifest file re available in the PackageInfo class.
To get an instance of PackageInfo with the fields for your app we will have to utilize the PackageManager class.

PackageManager pm=new PackageManager();
PackageInfo info=pm.getPackageInfo(getPackageName(),0);
Log.d("TestApp", "version name "+info.versionName);
Log.d("TestApp","version code "+info.versionCode);

Note that getPackageInfo takes 2 arguments. The first is the name of the package from which we want to get the version.
The method Context.getPackageName() gives us the name of the package for the current app (actually the app in the calling context).
The second are flags indicating what king of extra information we want. In our case 0 is sufficient but if you want to know more, check the documentation.

That's it, see you next time!

Programming tricks and tips for android developers