Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Checking for permissions

To respond to the system dialog, you write a corresponding implementation of
onRequestPermissionsResult(...). Android will call this callback when the user presses ALLOW or
DENY. Write an implementation that checks permission again and calls findImage() if the permission
was granted.


Listing 33.21  Responding to a permissions request result


(LocatrFragment.java)


@Override
public boolean onOptionsItemSelected(MenuItem item) {
...
}


@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
switch (requestCode) {
case REQUEST_LOCATION_PERMISSIONS:
if (hasLocationPermission()) {
findImage();
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}


private void findImage() {
LocationRequest request = LocationRequest.create();
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
request.setNumUpdates(1);


The callback to onRequestPermissionsResult(int,String[],int[]) includes a parameter called
grantResults. If you like, you can check this parameter to see whether your permission was granted.
Here, you take a slightly simpler approach: When you call hasLocationPermission(), its call to
checkSelfPermission(...) will also tell you whether you have acquired the permission. So you can call
hasLocationPermission() one more time and accomplish the same thing with less code than it takes
to look into the contents of grantResults.

Free download pdf