//权限数组(申请定位)
private String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS};
//返回code
private static final int OPEN_SET_REQUEST_CODE = 100;
//调用此方法判断是否拥有权限
private void initPermissions() {
if (lacksPermission(permissions)) {//判断是否拥有权限
//请求权限,第二参数权限String数据,第三个参数是请求码便于在onRequestPermissionsResult 方法中根据code进行判断
ActivityCompat.requestPermissions(this, permissions, OPEN_SET_REQUEST_CODE);
} else {
//拥有权限执行操作
initLocationOption();
}
}
//如果返回true表示缺少权限
public boolean lacksPermission(String[] permissions) {
for (String permission : permissions) {
//判断是否缺少权限,true=缺少权限
if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return true;
}
}
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {//响应Code
case OPEN_SET_REQUEST_CODE:
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "未拥有定位权限", Toast.LENGTH_LONG).show();
return;
}
}
//拥有权限执行操作
initLocationOption();
} else {
Toast.makeText(context, "未拥有定位权限", Toast.LENGTH_LONG).show();
}
break;
}
}
Adnroid动态申请定位权限
最新推荐文章于 2024-06-01 17:46:04 发布