7heViking
7heViking

Reputation: 7587

Get android app version code (major, minor and patch) at runtime

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.

Upvotes: 1

Views: 2919

Answers (2)

SAM
SAM

Reputation: 399

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;

Upvotes: 3

shkschneider
shkschneider

Reputation: 18253

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.

Upvotes: 4

Related Questions