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.

2
  • This question is already answered here: stackoverflow.com/questions/4616095/… Commented Jun 12, 2015 at 9: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. Commented Jun 12, 2015 at 10:42

2 Answers 2

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.

2
  • The problem was actually that I didn't know that versionName was what I needed.
    – 7heViking
    Commented Jun 12, 2015 at 11:38
  • 1
    I had to escape the dot to make this work, ie.: final String[] versionNames = versionName.split("\\."); Commented Mar 14, 2016 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;

Not the answer you're looking for? Browse other questions tagged or ask your own question.