i'm trying to implement Marshmallow's permission support, but my code inside "onRequestPermissionsResult" is never called.
When working in an Activity its working but in fragment I am facing the problem i.e, the control is not coming in onRequestPermissionsResult()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCheckPermission();
}
In the mCheckPermission():-
public void mCheckPermission() {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
PERMISSION_REQUEST_COARSE_LOCATION );
}
}
The dialog pops up with 2 buttons. DENY and ALLOW. When clicking on the button the controls is not coming inside the onRequestPermissionCheck();
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "permission granted", Toast.LENGTH_LONG).show();
//call your action
} else {
Toast.makeText(getActivity(), "permission denied", Toast.LENGTH_LONG).show();
}
break;
}
}
}
Instead of using the activity version of requestPermission
, you need to use the support.v4.app.fragment
requestPermission.
Fragment Request Permission
Change
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_CONTACTS}, REQUEST_CONTACT);
To
requestPermissions(new String[] {android.Manifest.permission.READ_CONTACTS}, REQUEST_CONTACT);
and onRequestPermissionsResult will be called properly.
Credits
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With