In my android project, I use this code to check & request runtime permissions:
public class AgentsFragmentMapTab extends RootFragment implements ActivityCompat.OnRequestPermissionsResultCallback
{
//..
private boolean checkAndRequestPermissions() {
int internet = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.INTERNET);
int loc = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION);
int loc2 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (internet != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.INTERNET);
}
if (loc != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
}
if (loc2 != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (BuildConfig.DEBUG)
Log.d(TAG, "checkAndRequestPermissions_listPermissionsNeeded(" + listPermissionsNeeded.size() + ")");
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(getActivity(), listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), LOCATION_REQ_CODE);
return false;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == LOCATION_REQ_CODE) {
} else {
}
}
}
This code shows the permission dialog perfectly. But when I click on the Allow or Deny button, the method onRequestPermissionsResult()
doesn't get invoked. Why isn't it getting invoked and how to achieve this?
Firstly, do this in the parent activity.
Then in your fragment, add a public method like so:
Change
to:
And also
ContextCompat
toActivityCompat
andgetActivity()
togetContext()
like:As mentioned in comments Override
onRequestPermissionsResult
in the parent activityMake sure to call
super.onRequestPermissionsResult
from this activity'sonRequestPermissionsResult
it will then send to your fragments which override
onRequestPermissionsResult
Edited :
Here is what i did
i called
requestPermissions(StringOfPermissions,YourRequestCode);
inside the fragment
And Here is the code i used to add the fragment inside the activity , pretty straight forward
I overridden onRequestPermissionsResult():
inside the activity and fragment
when i requested from the fragment it entered the activity and then it entered the fragment