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

(gtxtreme123) #1
Checking for permissions

Write a method to check whether you have access to the first permission in your
LOCATION_PERMISSIONS array.


Listing 33.18  Writing a permission check (LocatrFragment.java)


private void findImage() {
...
}


private boolean hasLocationPermission() {
int result = ContextCompat
.checkSelfPermission(getActivity(), LOCATION_PERMISSIONS[0]);
return result == PackageManager.PERMISSION_GRANTED;
}
}


Because checkSelfPermission(...) is a relatively new method on Activity, introduced in
Marshmallow, you use ContextCompat’s checkSelfPermission(...) instead to avoid ugly conditional
code. It will take care of the compatibility behavior for you.


Next, add a check before calling findImage() to make sure you have the permission.


Listing 33.19  Adding a permission check (LocatrFragment.java)


@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_locate:
if (hasLocationPermission()) {
findImage();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Free download pdf