versionCode
public int versionCodepinfo.versioncode was deprecated in API level 28 (Added in API level 1).
Use getLongVersionCode() instead, which includes both this and the additional versionCodeMajor attribute. The version number of this package, as specified by the <manifest> tag's versionCode attribute.
'versionCode' is deprecated as of API 28: Android 9.0 (Pie) |
getLongVersionCode is an API 28 method, though, so consider using PackageInfoCompat. It has one static method : getLongVersionCode(PackageInfo info)
PackageInfoCompat.getLongVersionCode (PackageInfo info)
public static long getLongVersionCode (PackageInfo info)Return R.attr.versionCode and R.attr.versionCodeMajor combined together as a single long value. The versionCodeMajor is placed in the upper 32 bits on Android P or newer, otherwise these bits are all set to 0.
Recommended solution:
If your have included below appcompat dependency this in your app level build.gradle :
implementation 'androidx.appcompat:appcompat:1.0.2'
then just use this function code:
public static long appVersionCode() {
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
long longVersionCode= PackageInfoCompat.getLongVersionCode(pInfo);
return (int) longVersionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return 0;
}
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
long longVersionCode= PackageInfoCompat.getLongVersionCode(pInfo);
return (int) longVersionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return 0;
}
Alternative solution in case you have not used appcompat library then just use as below :
final PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
int versionCode;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
versionCode = (int) pInfo.getLongVersionCode(); // avoid huge version numbers and you will be ok
} else {
//noinspection deprecation
versionCode = pInfo.versionCode;
}
int versionCode;
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
versionCode = (int) pInfo.getLongVersionCode(); // avoid huge version numbers and you will be ok
} else {
//noinspection deprecation
versionCode = pInfo.versionCode;
}
No comments:
Post a Comment