我推荐的解决方案:
将此包含在您的主要 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;
}