There seems to be a lot of confusion amongst developers how to get persistible permissions when using the SAF. Wasted some hours on this, so it is worth a note here.

To get the average file open dialog using the SAF, one could do this:

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
startActivityForResult(i, 0);

That works perfectly fine, but after a reboot, the permissions are gone, and opening the same file (without opening the dialog again) will fail. There are lots of resources on the Internet that tell developers to add some arguments when calling the Intent. This is wrong! Passing these to the intent is completely useless:

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // Don't do this
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); // Also no!
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION); // NO!

Instead, a single call to takePersistableUriPermission will retain permissions even after a reboot:

protected void onPropertyRequestResult(int propertyRequestCode, int resultCode, Intent data) {
    getContentResolver().takePersistableUriPermission(data.getData(), Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top