Android 多权限动态申请的优化
最近,在看其他项目代码中,发现多权限的申请方法,有缺陷,判断是只判断的其中一个是否有权限,这就有问题,另外,失败的话,是全部返回失败,并没有得到到底哪一个失败了。所以自己完善优化下多权限申请。
/**
* 多权限申请
* @param permissions 权限组
* @param messageRes 提示语组
*/
public void checkPermissions(String[] permissions, @StringRes int[] messageRes, PermissionCallBack callBack) {
this.mPermissionCallBack = callBack;
List<String> needPermissions = new ArrayList<>();
needPermissions = getDeniedPermissions(permissions,messageRes);
if(needPermissions == null||needPermissions.size() == 0){
//已经拥有授权
callBack.onSuccess();
} else {
ActivityCompat.requestPermissions(this, needPermissions.toArray(new String[needPermissions.size()]),
BaseConfig.ACTION_PERMISSIONS_REQUEST);
}
}
/**
* 获得权限组需要申请的权限
* @param permissions
* @param messageRes
* @return
*/
public List<String> getDeniedPermissions(String[] permissions, @StringRes int[] messageRes) {
List<String> needRequestPermissionList = new ArrayList<>();
// 检查是否已经具有权限
for (int i = 0; i<permissions.length;i++) {
if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
needRequestPermissionList.add(permissions[i]);
}
}
return needRequestPermissionList;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case BaseConfig.ACTION_PERMISSIONS_REQUEST: {
List<String> refusedPermissions = new ArrayList<>();
if (grantResults.length > 0 && verifyPermissions(grantResults)) {
// 全部授权操作
if (mPermissionCallBack != null) {
mPermissionCallBack.onSuccess();
}
} else {
// 多权限返回哪个是被拒绝
for(int i = 0;i<permissions.length;i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED)
refusedPermissions.add(permissions[i]);
}
//权限没能授权通过,可以考虑弹个toast告诉用户
if (mPermissionCallBack != null) {
mPermissionCallBack.onFailed(refusedPermissions);
}
}
break;
}
default:
break;
}
}
/**
* 确认所有的权限是否都已授权
*
* @param grantResults
* @return
*/
private boolean verifyPermissions(int[] grantResults) {
for (int grantResult : grantResults) {
if (grantResult != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
方法如何使用
checkPermissions(permissions,messageRes, new PermissionCallBack() {
@Override
public void onSuccess() {
// 操作获得手机权限后的方法
// 开启定位
}
@Override
public void onFailed(List<String> refusedPermissions) {
boolean isRefusedPhone = false,isRefusedLocation = false;
for(String refusedPermission : refusedPermissions) {
if (refusedPermission.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
isRefusedLocation = true;
} else if(refusedPermission.equals(Manifest.permission.READ_PHONE_STATE)){
isRefusedPhone = true;
}
}
if(!isRefusedPhone) {
// 操作获得手机权限后的方法
}
if(!isRefusedLocation) {
// 开启定位
}
}
});