Android SDK 28 - PackageInfo中的versionCode已被弃用

问题描述 投票:9回答:2

我刚刚将我的应用程序的compileSdkVersion升级到28(Pie)。

我收到了编译警告:

警告:不推荐使用PackageInfo中的[deprecation] versionCode

警告来自此代码:

final PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
int versionCode = info.versionCode;

我查看了documentation,但它没有说明如何解决此问题或应该使用什么而不是弃用字段。

android android-9.0-pie package-info
2个回答
24
投票

它说什么做on the Java doc(我建议不要使用Kotlin文档太多;它并没有真正保持良好):

的versionCode

此字段在API级别28中已弃用。请改用getLongVersionCode(),其中包括this和其他versionCodeMajor属性。此包的版本号,由标记的versionCode属性指定。

这是一个API 28方法,所以考虑使用PackageInfoCompat。它有一个静态方法:

getLongVersionCode(PackageInfo info)

21
投票

我推荐的解决方案

将它包含在main build.gradle中:

implementation 'androidx.appcompat:appcompat:1.0.2'

然后只需使用此代码:

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

如果您在添加appcompat库时遇到问题,请使用此替代解决方案:

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

0
投票

这里kotlin的解决方案:

val versionCode: Long =
    if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
           packageManager.getPackageInfo(packageName, 0).longVersionCode
    } else {
            packageManager.getPackageInfo(packageName, 0).versionCode.toLong()
    }
© www.soinside.com 2019 - 2024. All rights reserved.