Android SDK 28 - versionCode in PackageInfo has been deprecated

前端 未结 4 918
既然无缘
既然无缘 2021-01-07 16:08

I just upgraded my app\'s compileSdkVersion to 28 (Pie).

I\'m getting a compilation warning:

warning: [deprecation]

4条回答
  •  南笙
    南笙 (楼主)
    2021-01-07 16:46

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

提交回复
热议问题