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.
Asked
Active
Viewed 2,312 times
1
-
This question is already answered here: http://stackoverflow.com/questions/4616095/how-to-get-the-build-version-number-of-your-android-application – Stefan Wanitzek Jun 12 '15 at 09:46
-
2The `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. – CommonsWare Jun 12 '15 at 10:42
2 Answers
4
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.

shkschneider
- 17,833
- 13
- 59
- 112
-
The problem was actually that I didn't know that versionName was what I needed. – 7heViking Jun 12 '15 at 11:38
-
1I had to escape the dot to make this work, ie.: final String[] versionNames = versionName.split("\\."); – Stephan Henningsen Mar 14 '16 at 13:15
3
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;

Farshid Ahmadi
- 437
- 6
- 23

SAM
- 399
- 2
- 9