使用运行时权限检查,可以在用户选择完位置权限之后检查用户的选择并作出相应处理。代码示例:
// check location permission
if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// Location permission is granted
// Do your stuff here
} else {
// Location permission is not granted
// Ask for the permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
// MY_PERMISSIONS_REQUEST_LOCATION is an
// app-defined int constant. The callback method gets the
// result of the request.
}
//Handle the result of permission request
@Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
// Do your stuff here
} else {
// permission denied
// Do your stuff here
}
return;
}
// other 'case' lines to check for other
// permissions this app might request.
}
}