Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onRequestPermissionsResult not working in fragment

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;
            }
        }
    }
like image 842
Kanishka Sen Avatar asked May 16 '17 11:05

Kanishka Sen


1 Answers

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

like image 72
JARVIS Avatar answered Oct 13 '22 21:10

JARVIS