How to check permission in fragment

前端 未结 9 1933
执念已碎
执念已碎 2020-12-01 03:49

I want to check a permission inside a fragment.

my code:

        // Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPe         


        
9条回答
  •  無奈伤痛
    2020-12-01 04:36

    What worked for me was calling the onRequestPermissionsResult method in the activity inside which fragment is implemented rather than calling it in fragment itself. Inside onCreateView method in fragment:

        Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE);
    
                if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
                }else{
                    //Do your work
                    fetchMethod();
                }
    
            }
    });
    

    In the Activity which helps to implement fragment, outside of onCreate method:

        @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_MEDIA:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    fetchMethod();
    
                }else{
                    Toast.makeText(getApplicationContext(), "Permission not granted!", Toast.LENGTH_SHORT).show();
                }
                break;
    
            default:
                break;
        }
    }
    

提交回复
热议问题