onRequestPermissionsResult not being called in fragment if defined in both fragment and activity
Edited answer to cover broader issues
I think you are confusing the method for fragment and activity. Had a similar issue my project last month. Please check if you have finally the following:
- In AppCompatActivity use the method ActivityCompat.requestpermissions
- In v4 support fragment you should use requestpermissions
- Catch is if you call AppcompatActivity.requestpermissions in your fragment then callback will come to activity and not fragment
- Make sure to call
super.onRequestPermissionsResult
from the activity'sonRequestPermissionsResult
.
See if it helps .
I requested location permission from a fragment and in the fragment, I needed to change this:
ActivityCompat.requestPermissions(getActivity(), new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQ_CODE);
to this:
requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_REQ_CODE);
then the onRequestPermissionsResult was called in the fragment.
This is a common mistake that people make when coding for marshmallow.
When in AppCompatActivity, you should use ActivityCompat.requestPermissions; When in android.support.v4.app.Fragment, you should use simply requestPermissions (this is an instance method of android.support.v4.app.Fragment) If you call ActivityCompat.requestPermissions in a fragment, the onRequestPermissionsResult callback is called on the activity and not the fragment.
requestPermissions(permissions, PERMISSIONS_CODE);
If you are calling this code from a fragment it has it’s own requestPermissions method.
So basic concept is, If you are in an Activity, then call
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
and if in a Fragment, just call
requestPermissions(new String[]{Manifest.permission.CAMERA},
MY_PERMISSIONS_REQUEST_CAMERA);
For the reference, I have obtained the answer from this link https://www.coderzheaven.com/2016/10/12/onrequestpermissionsresult-not-called-on-fragments/