onRequestPermissionsResult not working in fragment
Asked Answered
P

1

15

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;
            }
        }
    }
Progesterone answered 16/5, 2017 at 11:0 Comment(3)
refer #35989788Populace
I have already called requestpermissions() and I am not calling ActivityCompat.requestpermission();Progesterone
1. If you overridden the activity's onRequestPermissionsResult then call it's super.onRequestPermissionsResult. 2. Try to remove the fragment's super.onRequestPermissionsResult(requestCode, permissions, grantResults); or just put it to the end of the function.Away
S
40

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

Scribner answered 10/9, 2018 at 16:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.