Search code examples
androidandroid-permissionsandroid-fileproviderandroid-11android-storage

How to select Android Allow management of all Files option by default?


I am accessing files with the below set of codes. But for Android 11, it works only after manually enabling "Allow management of All files" from the application info screen.

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            
            path = FileProvider.getUriForFile(getApplicationContext(), getApplicationContext().getPackageName() + ".helper.ProviderClass", contentUri);
            intent = new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(path, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(intent);
        } else {
            path = Uri.fromFile(contentUri);
            intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(path, "application/pdf");
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(intent);
        }

Anyone, please suggest a better solution to enable that option automatically.


Solution

  • your current code in if else is in fact the same (besides file URI)... new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION) sets up action for this Intent, but one line below you have overwritting this value with setAction call

    consider detecting your permission state on Android 11, when not granted then use

    startActivity(new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION));
    

    this will pass user to proper settings screen where permission must be granted manually by user, thats current system policy. then after getting back to app check again for permission, if now is granted (user enabled) then run your view file intent

    some related doc in HERE