1

on Android os 5.11 (maybe other os as well), When using Intent.ACTION_GET_CONTENT to list the files with Android system file picker,

Intent openIntent = new Intent(Intent.ACTION_GET_CONTENT);
openIntent.addCategory(Intent.CATEGORY_OPENABLE);
openIntent.setType("*/*");
startActivityForResult(openIntent, ANDROID_FILE_PICKER);

and in void onActivityResult() it got SecurityException:

"Permission Denial: opening provider com.google.android.apps.docs.storagebackend.StorageBackendContentProvider... requires android.permission.MANAGE_DOCUMENTS"

The work around for the exception is:

Intent openIntent = new Intent(Intent.ACTION_GET_CONTENT);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        openIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        openIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    }
    openIntent.addCategory(Intent.CATEGORY_OPENABLE);
    openIntent.setType("*/*");
    startActivityForResult(openIntent, ANDROID_FILE_PICKER);

and in onActivityResult(), do:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
     int takeFlags = data.getFlags();
     takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
     getContentResolver().takePersistableUriPermission(uri, takeFlags);

it resolved the permission issue.

But it is worse that the changing from using Intent.ACTION_GET_CONTENT to Intent.ACTION_OPEN_DOCUMENT causes the Android's system file picker menu does not show the content providers, like Dropbox, Photos, etc.

(as pointed out in the Who to show more providers with ACTION_OPEN_DOCUMENT).

So the question is if it has to list the Dropbox etc. with using the Intent.ACTION_GET_CONTENT, but how to avoid getting the SecurityException?

Community
  • 1
  • 1
lannyf
  • 9,865
  • 12
  • 70
  • 152

1 Answers1

1

seems this works. there must be better solution if someone knows:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    try {
        this.grantUriPermission(
                this.getPackageName(),
                uri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
        );
    } catch (IllegalArgumentException e) {
        this.grantUriPermission(
                this.getPackageName(),
                uri,
                Intent.FLAG_GRANT_READ_URI_PERMISSION
        );  // kikat api only 0x3 are
        // allowed FLAG_GRANT_READ_URI_PERMISSION = 1 | FLAG_GRANT_WRITE_URI_PERMISSION = 2;
    } catch (SecurityException e) {
        // ignore
    }

    int takeFlags = data.getFlags();
    takeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

    try {
        getContentResolver().takePersistableUriPermission(uri, takeFlags);
    } catch (SecurityException e) {
        // ignore
    }
}
vovahost
  • 34,185
  • 17
  • 113
  • 116
lannyf
  • 9,865
  • 12
  • 70
  • 152