Android SDK 28 - versionCode in PackageInfo has been deprecated

ε祈祈猫儿з 提交于 2019-12-01 14:59:05

It says what to do on the Java doc (I recommend not using the Kotlin documentation for much; it's not really maintained well):

versionCode

This field was deprecated in API level 28. Use getLongVersionCode() instead, which includes both this and the additional versionCodeMajor attribute. The version number of this package, as specified by the tag's versionCode attribute.

This is an API 28 method, though, so consider using PackageInfoCompat. It has one static method:

getLongVersionCode(PackageInfo info)
Blackd

My recommended solution:

Include this in your main build.gradle :

implementation 'androidx.appcompat:appcompat:1.0.2'

then just use this code:

PackageInfo pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
long longVersionCode= PackageInfoCompat.getLongVersionCode(pInfo);
int versionCode = (int) longVersionCode; // avoid huge version numbers and you will be ok

In case you have problems adding appcompat library then just use this alternative solution:

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

Here the solution in kotlin:

val versionCode: Long =
    if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
           packageManager.getPackageInfo(packageName, 0).longVersionCode
    } else {
            packageManager.getPackageInfo(packageName, 0).versionCode.toLong()
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!