sunita
sunita

Reputation: 480

onRequestPermissionsResult is not called in fragment android

i am taking runtime permission from user by using below code in fragment .

if (ContextCompat.checkSelfPermission(getActivity(),
                                    Manifest.permission.READ_EXTERNAL_STORAGE)
                                    != PackageManager.PERMISSION_GRANTED) {


                                ActivityCompat.requestPermissions(mActivity,
                                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                        STORAGE_PERMISSION_CODE);


                            }

and overriding

@Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 21: {

                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.




                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_SHORT).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

but override method not called

please give me hint for that i have to override in fragment

Upvotes: 5

Views: 12657

Answers (7)

Basawa Reddy
Basawa Reddy

Reputation: 1

To handle permissions in a Fragment call requestPermissions method. If you override onRequestPermissionsResult method in both fragment and activity, containing that fragment, make sure to call super.onRequestPermissionsResult(...) in the activity method to propagate call to the onRequestPermissionsResult method in the fragment.

Upvotes: 0

Rakshit
Rakshit

Reputation: 46

when Request for Permission from fragment

  • Kotlin

    requireActivity().requestPermissions(<Permission array>, <Request code>)

  • Java

    getActivity().requestPermissions(<Permission array>, <Request code>)

You can call fragment onRequestPermissionsResult from activity's onRequestPermissionsResult

  • Kotlin
        var fragments:List? = supportFragmentManager.fragments
        var lastFragment:Fragment? = if(fragments!=null && fragments.size>0) fragments.get(fragments.size-1) else null
        var lastFragmentName:String? = if(lastFragment!=null) lastFragment.javaClass.name else ""
    
        if (lastFragmentName.equals("com.example.YourFragment")){
            lastFragment?.onRequestPermissionsResult(requestCode,permissions,grantResults)
        }
  • Java
        List fragments = getSupportFragmentManager().getFragments();
        Fragment lastFragment = (fragments!=null && fragments.size()>0)?fragments.get(fragments.size()-1) : null;
        String lastFragmentName = (lastFragment!=null) ? lastFragment.getClass().getName() : "";
if (lastFragment!=null && lastFragmentName.equals("com.example.YourFragment")){ lastFragment.onRequestPermissionsResult(requestCode,permissions,grantResults); }

Upvotes: 0

Abhijith Brumal
Abhijith Brumal

Reputation: 1772

I had the same issue,

It is a common mistake and it is very simple to solve.

if you are in an activity we normally use ActivityCompat.requestPermissions(activity, permissionsNeeded.toTypedArray(),PERMISSION_REQUEST_CODE)

But you shouldn't use the same for a fragment. You can simply use it like requestPermissions(permissionsNeeded.toTypedArray(),PERMISSION_REQUEST_CODE)

If you call the Activity.requestPermission in fragment, the on request callback is get called in the Activity not in the Fragment.

Happy coding

Upvotes: 0

Embydextrous
Embydextrous

Reputation: 1661

Use FragmentCompat instead of ActivityCompat.

Upvotes: 1

Rodriquez
Rodriquez

Reputation: 1001

Becouse remember for futher u must do this in ACTIVITY not in a fragment. Yoou can d this tricky in fragment but this is bad way

this is in Activity. I check permissions and save it

private static final int REQUEST_CODE_GET_ACCOUNTS = 101;
    private static final int REQUEST_AUDIO_PERMISSION = 102;

 @TargetApi(23)
public void checkAudioPermission() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        playerFragment.setupVisualizerFxAndUI();
        return;
    }
    if (this.checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager
            .PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},
                REQUEST_AUDIO_PERMISSION);
    } else {
        playerFragment.setupVisualizerFxAndUI();
    }
}

@TargetApi(23)
public void checkGmailPermission() {
    if (isDeviceOnline()) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            showGmailRecFragment(true);
            return;
        }
        if (this.checkSelfPermission(Manifest.permission.GET_ACCOUNTS) != PackageManager
                .PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.GET_ACCOUNTS},
                    REQUEST_CODE_GET_ACCOUNTS);
            return;
        } else {
            showGmailRecFragment(true);
        }
    } else {
        Utils.showToast(this, getString(R.string.no_internet));
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[]
        grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_GET_ACCOUNTS:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                showGmailRecFragment(true);
            } else {
                Utils.showToast(this, getString(R.string.accounts_permision_denied));
            }
            break;
        case REQUEST_AUDIO_PERMISSION:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                playerFragment.setupVisualizerFxAndUI();
            } else {
                Utils.showToast(this, getString(R.string.audio_permission_denied));
            }
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            break;
    }
}

and this is on fragment when i want check permission again or if user denied it. Also this save the permissions

private void setupViewVisualizer() {
    if (!isLiveTv && !homeVideo.isVideoType()) {
        ((PlayerActivity) activity).checkAudioPermission();
    } else {
        return;
    }
}

Upvotes: 0

Arjun saini
Arjun saini

Reputation: 4182

Try this..

 private static final int REQUEST_RUNTIME_PERMISSION = 123;

if (CheckPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)) {
// you have permission go ahead

} else {
// you do not have permission go request runtime permissions
RequestPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE, REQUEST_RUNTIME_PERMISSION);
}


  @Override
    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {

        switch (permsRequestCode) {

            case REQUEST_RUNTIME_PERMISSION: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    // you do not have permission show toast.
                }
                return;
            }
        }
    }
    public void RequestPermission(Activity thisActivity, String Permission, int Code) {
        if (ContextCompat.checkSelfPermission(thisActivity,
                Permission)
                != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
                    Permission)) {

            } else {
                ActivityCompat.requestPermissions(thisActivity,
                        new String[]{Permission},
                        Code);
            }
        }
    }

    public boolean CheckPermission(Activity context, String Permission) {
        if (ContextCompat.checkSelfPermission(context,
                Permission) == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

Upvotes: 0

Jinal Patel
Jinal Patel

Reputation: 709

Use this code for Fragment

 private void requestReadExternalStorageCameraPermission() {
    if (FragmentCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
        Toast.show(getActivity(), getString(R.string.toast_permission), Toast.ToastType.ALERT);
    } else {
        FragmentCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE_CAMERA);
    }
}

and

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
                                       int[] grantResults) {
    switch (requestCode) {
        case PERMISSION_REQUEST_CODE_GALLARY:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                captureImageInitialization(1);
            }
            break;
        case PERMISSION_REQUEST_CODE_CAMERA:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
                captureImageInitialization(0);
            }


            break;
        default:
            break;
    }
}

Upvotes: 0

Related Questions