How to check if Manifest.permission.MANAGE_EXTERNAL_STORAGE is granted?

Viewed 2090

How to check if the Manifest.permission.MANAGE_EXTERNAL_STORAGE permission has been granted? I have tried the following but it does not work:

ContextCompat.checkSelfPermission(context, 
  "Manifest.permission.MANAGE_EXTERNAL_STORAGE")
  == PackageManager.PERMISSION_GRANTED

The above code always returns false, despite the permission has been granted. Any help appreciated, thanks!

3 Answers

As CommonsWare Said, You can use isExternalStorageManager()

Returns whether the calling app has All Files Access on the primary shared/external storage media. Declaring the permission Manifest.permission.MANAGE_EXTERNAL_STORAGE isn't enough to gain the access. To request access, use android.provider.Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION.

Example

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
        if(!Environment.isExternalStorageManager())
        {
              try {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.setData(Uri.parse(String.format("package:%s", getApplicationContext().getPackageName())));
                    storagePermissionRequest.launch(intent);
                } catch (Exception e) {
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                    storagePermissionRequest.launch(intent);
                }
        }
    }

Result Contracts. ActivityResultContracts

ActivityResultLauncher<Intent> storagePermissionRequest = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                        if (!Environment.isExternalStorageManager()) {
                            showPermissionDeniedDialog();
                        }
                    }
                }
            });

I hope it will helpful to others.

if (ContextCompat.checkSelfPermission(
                requireContext(),  
                Manifest.permission. MANAGE_EXTERNAL_STORAGE //Android 10, WRITE_EXTERNAL_STORAGE for older
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissions(
                arrayOf(Manifest.permission. MANAGE_EXTERNAL_STORAGE),
                REQUEST_CODE. // you can use it then in onActivityResult() etc.
            )
        } else {
             doSomething() //now you have permission
        }
Related