Reputation: 7587
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
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
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