Chapter 33 Locations and Play Services
Now to write what should happen when you do not have location permission. In that case, you want to
call the requestPermissions(...) method.
Listing 33.20 Requesting permission (LocatrFragment.java)
public class LocatrFragment extends Fragment {
private static final String TAG = "LocatrFragment";
private static final String[] LOCATION_PERMISSIONS = new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
};
private static final int REQUEST_LOCATION_PERMISSIONS = 0;
...
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_locate:
if (hasLocationPermission()) {
findImage();
} else {
requestPermissions(LOCATION_PERMISSIONS,
REQUEST_LOCATION_PERMISSIONS);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
The requestPermissions(...) method is an asynchronous request. When you call it, Android will
display the system permissions dialog with a message appropriate to the permission you are requesting.