例如
申请定位权限:
if (Build.VERSION.SDK_INT >=M && !hasPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
String[] permissions =new String[1];
permissions[0] = Manifest.permission.ACCESS_COARSE_LOCATION;
Log.e("TAG", "onRequestPermissionsResult 申请权限");
//申请权限
ActivityCompat.requestPermissions(this, permissions,MY_LBS_PERMISSION_REQUEST_CODE);
}
//处理权限请求
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode ==MY_LBS_PERMISSION_REQUEST_CODE) {
boolean isAllGranted =true;
for (int grant : grantResults) {
if (grant != PackageManager.PERMISSION_GRANTED) {
isAllGranted =false;
break;
}
}
if (isAllGranted) {
Log.e("TAG", "onRequestPermissionsResult 同意");
}else {
List notAsk =new ArrayList<>();
for (String permission : permissions) {
Log.e("TAG", "onRequestPermissionsResult - 循环 -");
if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permission)
&& ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
notAsk.add(permission);
}
}
if (notAsk.size() >0) {//拒绝不再提醒
Log.e("TAG", "onRequestPermissionsResult 拒绝不再提醒");
}else {
Log.e("TAG", "onRequestPermissionsResult 本次拒绝");
}
}
}
}
/**
* 检查是否有某个权限
* @param context context
* @param permission 权限
* @return true means has
*/
public static boolean hasPermission(Context context, String permission) {
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}