我正在研究 Android-M 运行时权限。我想为我的一个片段添加位置权限。这是我的代码。Android 请求许可,但即使我拒绝许可,也没有任何反应,它会关闭对话框,但仍然activateGPS()
有效并返回值。提前致谢。
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
getPermissionToReadUserContacts();
} else {
// Pre-Marshmallow
System.out.println("CODMOB: Device not marshmallow");
activateGPS();
}
activateGPS();
return view;
}
private static final int LOCATION_PERMISSIONS_REQUEST = 1;
public void getPermissionToReadUserContacts() {
System.out.println("CODMOB: getPermissionToReadUserContacts()");
// 1) Use the support library version ContextCompat.checkSelfPermission(...) to avoid
// checking the build version since Context.checkSelfPermission(...) is only available
// in Marshmallow
// 2) Always check for permission (even if permission has already been granted)
// since the user can revoke permissions at any time through Settings
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// The permission is NOT already granted.
// Check if the user has been asked about this permission already and denied
// it. If so, we want to give more explanation about why the permission is needed.
System.out.println("CODMOB: The permission is NOT already granted.");
if (shouldShowRequestPermissionRationale(
Manifest.permission.ACCESS_COARSE_LOCATION)) {
// Show our own UI to explain to the user why we need to read the contacts
// before actually requesting the permission and showing the default UI
System.out.println("CODMOB: We need to access location.");
}else{
// Fire off an async request to actually get the permission
// This will show the standard permission request dialog UI
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
LOCATION_PERMISSIONS_REQUEST);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// Make sure it's our original READ_CONTACTS request
if (requestCode == LOCATION_PERMISSIONS_REQUEST) {
if (grantResults.length>0 &&
grantResults[0] == PackageManager.PERMISSION_GRANTED) {
System.out.println("CODMOB:permission granted");
activateGPS();
//Toast.makeText(this, "Read Contacts permission granted", Toast.LENGTH_SHORT).show();
} else {
System.out.println("CODMOB: permission denied");
//Toast.makeText(this, "Read Contacts permission denied", Toast.LENGTH_SHORT).show();
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}