获取版本代码时没有虚方法 getLongVersionCode()J

say*_*bir 1 android nosuchmethoderror

根据谷歌的建议,我getLongVersionCode用来获取这样的版本代码:

private long getCurrentCode() {
    try {
        return context.getPackageManager()
                .getPackageInfo(context.getPackageName(), 0).getLongVersionCode();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

但是当我运行我的应用程序时,我的应用程序强制关闭并且出现此错误:

Process: com.xxxxx.debug, PID: 25754
    java.lang.NoSuchMethodError: No virtual method getLongVersionCode()J in class Landroid/content/pm/PackageInfo; or its super classes (declaration of 'android.content.pm.PackageInfo' appears in /system/framework/framework.jar)
        at com.xxxxx.common.ApplicationUpdateTask.getCurrentCode(ApplicationUpdateTask.java:329)
        at com.xxxxx.common.ApplicationUpdateTask.<init>(ApplicationUpdateTask.java:84)
Run Code Online (Sandbox Code Playgroud)

所以我决定使用:

String versionName = BuildConfig.VERSION_NAME;
Run Code Online (Sandbox Code Playgroud)

但是现在这个推荐回来了-1!!!!!!

这是我的 gradle 配置:

compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 66
        versionName '2.0.66'
        applicationId 'com.xxxxxx.yyyyy'
        multiDexEnabled true
    }
Run Code Online (Sandbox Code Playgroud)

Vít*_*ola 6

我建议您使用 PackageInfoCompat:

PackageInfoCompat.getLongVersionCode();
Run Code Online (Sandbox Code Playgroud)

它会自动检查大于 28 的 sdk 版本并适当地返回 versionCode 或 LongVersionCode。它包含在 androidx 中。