This is due to in Marshmallow (Android version 6.0) Users can choose to turn off permissions. Simply wrap this check to see if the permission is enabled before your location code.
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
}
You should also write in an else statement request code which will request the permission from the user if they haven't got it.
Here's a nice request permissions method:
public void requestPermissions(List<String> permissions, ActivityCompat.OnRequestPermissionsResultCallback onRequestPermissionsResultCallback) {
String[] params = permissions.toArray(new String[permissions.size()]);
requestPermissions(params, onRequestPermissionsResultCallback);
}
In your case you will have to pass it the Location permissions which you can get with this method:
private List<String> getRequiredLocationPermissions() {
String accessCoarsePermission = android.Manifest.permission.ACCESS_COARSE_LOCATION;
String accessFineLocationPermission = android.Manifest.permission.ACCESS_FINE_LOCATION;
int hasCoarsePermission = ContextCompat.checkSelfPermission(getActivity(), accessCoarsePermission);
int hasFineLocationPermission = ContextCompat.checkSelfPermission(getActivity(), accessFineLocationPermission);
List<String> permissions = new ArrayList<>();
if (hasCoarsePermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(accessCoarsePermission);
}
if (hasFineLocationPermission != PackageManager.PERMISSION_GRANTED) {
permissions.add(accessFineLocationPermission);
}
return permissions;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…