关于Android运行时权限的文章已经很多,一般看下官网的Requesting Permissions at Run Time就够了。
本篇主要记下使用过程中遇到的一个问题,项目中使用如下代码对检查权限是否被授予:
public boolean checkSelfPermissions(String... permissions) {
ArrayList<String> lackPermissions = new ArrayList<>();
for (String permission : permissions) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
lackPermissions.add(permission);
}
}
if (!lackPermissions.isEmpty()) {
//requestPermissions(permissionList.toArray(new String[permissionList.size()]));
return false;
}else {
return true;
}
}
一直也没出现问题,直至昨天遇到了异常,排查发现位置权限未授予的情况下checkSelfPermissions方法依然返回true,说明ContextCompat.checkSelfPermission没能正常返回。仔细看了下项目发现当前targetSdkVersion 22,又网上确认了下果然这货导致,修改targetSdkVersion >=23即可。
其实仅仅判断权限是否授予,不申请权限的话,也可以通过下面的方式解决:
public boolean selfPermissionGranted(String permission) {
// For Android < Android M, self permissions are always granted.
boolean result = true;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (targetSdkVersion >= Build.VERSION_CODES.M) {
// targetSdkVersion >= Android M, we can
// use Context#checkSelfPermission
result = ContextCompat.checkSelfPermission(this, permission)
== PackageManager.PERMISSION_GRANTED;
} else {
// targetSdkVersion < Android M, we have to use PermissionChecker
result = PermissionChecker.checkSelfPermission(this, permission)
== PermissionChecker.PERMISSION_GRANTED;
}
}
return result;
}