ITmob-Ly
发布于 2022-12-23 / 316 阅读
0

Android Exception - Package cn.itmob.demo new target SDK 21 doesn't support runtime permissions

1. 异常

安装应用时遇到如下情况的错误信息:

  1. 使用 PackageInstaller 安装应用时 Logcat 输出如下错误:
Package cn.itmob.demo new target SDK 21 doesn't support runtime permissions but the old target SDK 27 does.
  1. 使用 adb 安装应用时输入如下错误:
> adb install TestApp.apk
Performing Streamed Install
adb: failed to install TestApp.apk: Failure [-26: Package cn.itmob.demo new target SDK 21 doesn't support runtime permissions but the old target SDK 27 does.]

或者:

Installation error: INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE
Please check logcat output for more details.
Launch canceled!

2. 解决:

因为从 Android 6.0(API 级别 23) 版本开始,升级应用时新增了限制条件,如果已安装版本支持运行时权限(targetSDKVersion > 22)那么升级时的新版本的 targetSDKVerssion 也必须大于 22。

因为从 Android 6.0(API 级别 23)开始敏感权限不再是在安装时授予,但必须由应用程序在运行时通过 requestPermissions 请求。

如下是 Android 源码中关于改限制的代码:

InstallPackageHelper.java

if (replace) {
    // Prevent apps opting out from runtime permissions
    AndroidPackage oldPackage = mPm.mPackages.get(pkgName);
    final int oldTargetSdk = oldPackage.getTargetSdkVersion();
    final int newTargetSdk = parsedPackage.getTargetSdkVersion();
    if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1
            && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) {
        throw new PrepareFailure(
                PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE,
                "Package " + parsedPackage.getPackageName()
                        + " new target SDK " + newTargetSdk
                        + " doesn't support runtime permissions but the old"
                        + " target SDK " + oldTargetSdk + " does.");
    }
    ...
}

上面的错误信息就是因为已安装了 targetSDKVerssion 是 27 的应用,重新安装的应用 targetSDKVerssion 是 21。

解决办法:

  1. 修改新版本的 targetSDKVerssion,保证其不低于之前的版本
  2. 卸载旧版本重新安装

这个限制无法通过 adb install -radb install -d 来安装

> adb install -r -d TestApp.apk
Performing Streamed Install
adb: failed to install TestApp.apk: Failure [-26: Package cn.itmob.demo new target SDK 21 doesn't support runtime permissions but the old target SDK 27 does.]