有一些功能需要检验应用权限,但是再某些特定的场景下checkSelfPermission是失效的,这里的场景特指应用targetSdkVersion最高为22,手机系统版本为6.0及以上,安装的时候拒绝了一些权限,但是使用checkSelfPermission做权限校验的时候返回的还是true的问题,查阅了其他的博客发现对于系统6.0及以上校验权限需要需要判断targetSdkVersion的版本,代码如下
public static boolean selfPermissionGranted(Context context, String permission) {
boolean ret = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (targetSdkVersion >= Build.VERSION_CODES.M) {
ret = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
} else {
ret = PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED;
}
}
return ret;
}
上面的代码写得很明白,需要根据targetSdkVersion调用不同的方法校验权限。
本来以为已经解决了,结果测试的时候发现不行,关于targetSdkVersion 的判断一直是true,再改一下就好了
public static boolean selfPermissionGranted(Context context, String permission) {
boolean ret = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.M) {
ret = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
} else {
ret = PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED;
}
}
return ret;
}