为什么targetSdkVersion < 23 Context 的 checkSelfPermission失效
跟踪一下源码发现Context 的 checkSelfPermission最终会调用ContextImp的checkPermission,最终调用
@Override
public int checkPermission(String permission, int pid, int uid) {
if (permission == null) {
throw new IllegalArgumentException(“permission is null”);
}
try {
return ActivityManagerNative.getDefault().checkPermission(
permission, pid, uid);
} catch (RemoteException e) {
return PackageManager.PERMISSION_DENIED;
}
}
最终请求ActivityManagerService的checkPermission,经过预处理跟中转最后会调用PackageManagerService的checkUidPermission
@Override
public int checkUidPermission(String permName, int uid) {
final int userId = UserHandle.getUserId(uid);
synchronized (mPackages) {
Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
if (obj != null) {
final SettingBase ps = (SettingBase) obj;
final PermissionsState permissionsState = ps.getPermissionsState();
if (permissionsState.hasPermission(permName, userId)) {
return PackageManager.PERMISSION_GRANTED;
}
if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState
.hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) {
return PackageManager.PERMISSION_GRANTED;
}
} … }
return PackageManager.PERMISSION_DENIED;
}
PackageManagerService会从mSettings全局变量中获取权限,然后进一步验证权限是否被授予
public boolean hasPermission(String name, int userId) {
enforceValidUserId(userId);
if (mPermissions == null) {
return false;
}
PermissionData permissionData = mPermissions.get(name);
return permissionData != null && permissionData.isGranted(userId);
}
这里的检查点只有两点,第一个是是否有这个权限,第二是是否是Granted,对于targetSdkVersion<23的所有的权限都在packages.xml中,grante一直是true,无法被跟新,为什么无法被更新呢?看一下6.0之后的授权与取消授权的函数,首先看一个变量mAppSupportsRuntimePermissions
mAppSupportsRuntimePermissions = packageInfo.applicationInfo
.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1;
mAppOps = context.getSystemService(AppOpsManager.class);
mAppSupportsRuntimePermissions定义在AppPermissionGroup中,6.0之后权限都是分组的,对于targetSdkVersion<23的APP来说,很明显是不支持动