私は Android-M ランタイム権限に取り組んでいました。フラグメントの 1 つに場所のアクセス許可を追加したいと考えていました。これが私のコードです。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);
}
}