1

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.

7heViking
  • 7,137
  • 11
  • 50
  • 94
  • 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
  • 2
    The `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 Answers2

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
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