Explain Codes LogoExplain Codes Logo

Android M Permissions: onRequestPermissionsResult() not being called

java
android-permissions
request-permissions
onrequestpermissionresult
Alex KataevbyAlex Kataev·Aug 30, 2024
TLDR

Ensure specific override of onRequestPermissionsResult in the Activity or Fragment that made the permission request:

@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == YOUR_REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Great success! Move ahead, the road is clear. } else { // Oops! Permission denied. It's fallback time. } } }

Always use requestPermissions from the fragment not from the activity when the request is made from a fragment to ensure that the fragment's onRequestPermissionsResult gets triggered. Don't forget to ensure YOUR_REQUEST_CODE in the callback is your actual request code.

Mastering the requestPermissions call

The origin of your permission request dictates which requestPermissions method should be used. If the permission request originates from an Activity, use ActivityCompat.requestPermissions(). If from a Fragment, use Fragment.requestPermissions(). This ensures that onRequestPermissionsResult() is triggered in the correct context.

Counterintuitive manifest flags

Certain manifest flags may prevent onRequestPermissionsResult() from being called:

  1. android:noHistory="true": The Activity won't be on the back stack and so, can't receive the callback. If noHistory isn't crucial in your design, try removing it.
  2. android:excludeFromRecents="true": This flag can also hinder the callback. Use finishAndRemoveTask() to wave goodbye to your Activity after handling the permission request to achieve the same effect.

Method signature matters a lot

Double-check the signature of your callback method. Incorrect parameters or a typo can leave you waiting for a callback that will never come. In programming, even the slightest details matter!

Ensuring the chain of responsibility

Maintain the chain of responsibility. By implementing super.onRequestPermissionsResult() in both your activity and fragment you make sure that any unhandled permission request bubbles up to the calling parent.

Testing? Yes, on real devices

Ensure consistent permission handling across different device brands. Custom OS variations can sometimes cause unexpected behaviours. Always test your permission flows on real devices.

No delays, please

Design your Permission flows to be as smooth as possible. Verify any delays or blockers in the permission handling process. Upon permission grant, make sure it's a green light for subsequent actions like sending a text message.