How do you get the app version code at runtime? I have found many solutions to get the app version as a single integer. However I need the major.minor.patch version of the version code.
2 Answers
That would mean to get the versionName
that follows the semantic versioning principles.
Get the versionName
:
packageManager.getPackageInfo(packageName(), PackageManager.GET_META_DATA)
.versionName; // throws NameNotFoundException
Parse the versionName
:
// check versionName against ^\d+\.\d+\.\d+$
final String[] versionNames = versionName.split("\\.");
final Integer major = Integer.valueOf(versionNames[0]);
final Integer minor = Integer.valueOf(versionNames[1]);
final Integer patch = Integer.valueOf(versionNames[2]);
DO make sure to handle all possible errors.
-
The problem was actually that I didn't know that versionName was what I needed. Commented Jun 12, 2015 at 11:38
-
1I had to escape the dot to make this work, ie.: final String[] versionNames = versionName.split("\\."); Commented Mar 14, 2016 at 13:15
you get it by this way
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(
context.getPackageName(), 0);
String version = info.versionName;
int code = info.versionCode;
versionCode
is "a single integer". It has never been in the "major.minor.patch" format.versionName
could be in that format, but it does not have to be. There is no requirement for any developer of any Android app to use "major.minor.patch" for anything.