Android SDK 28 - PackageInfo 中的版本代码已被弃用

Android SDK 28 - versionCode in PackageInfo has been deprecated

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

我收到编译警告:

warning: [deprecation] versionCode in PackageInfo has been deprecated

警告来自此代码:

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

我查看了 documentation,但它没有说明如何解决此问题或应该使用什么来代替已弃用的字段。

它说明了要做什么 on the Java doc(我建议不要过多使用 Kotlin 文档;它维护得不是很好):

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.

不过,这是一个 API 28 方法,因此请考虑使用 PackageInfoCompat。它有一个静态方法:

getLongVersionCode(PackageInfo info)

我推荐的解决方案:

将此包含在您的主要内容中 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;
}

这里是kotlin中的解决方案:

val versionCode: Long =
    if (Build.VERSION.SDK_INT >= VERSION_CODES.P) {
           packageManager.getPackageInfo(packageName, 0).longVersionCode
    } else {
            packageManager.getPackageInfo(packageName, 0).versionCode.toLong()
    }

仅针对使用 Xamarin 的其他人,我的回答是:

public long GetBuild()
{
    var context = global::Android.App.Application.Context;
    PackageManager manager = context.PackageManager;
    PackageInfo info = manager.GetPackageInfo(context.PackageName, 0);

    return info.LongVersionCode;
}

Kotlin中获取PackageInfo中的versionCode的简单代码

val packageInfo = this.packageManager.getPackageInfo(this.packageName, 0)
val verCode = PackageInfoCompat.getLongVersionCode(packageInfo).toInt()