1

When requesting access to a folder (document-tree) via StorageAccessFramework, we use this code. I got this code from this repo and also seen in other questions on StackOverflow like this and this.

val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
    addFlags(
        Intent.FLAG_GRANT_READ_URI_PERMISSION
                or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
                or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
                or Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
    )
}

startActivityForResult(intent, 101)

4 flags are added to the intent so that read/write permissions to the folder are given and also so that those permissions are persisted (across device restarts). My question is, what is the purpose of the FLAG_GRANT_PREFIX_URI_PERMISSION flag?

As per the documentation, this is what it does -

When combined with FLAG_GRANT_READ_URI_PERMISSION and/or FLAG_GRANT_WRITE_URI_PERMISSION, the URI permission grant applies to any URI that is a prefix match against the original granted URI. (Without this flag, the URI must match exactly for access to be granted.) Another URI is considered a prefix match only when scheme, authority, and all path segments defined by the prefix are an exact match.

This leaves me with more questions than answers. Like what is a "prefix match" and what originally granted URI is the documentation referring to? Is this a flag which is useful when app requests permissions for a new folder?

Any clarification on this will be helpful. Thanks.

vepzfe
  • 4,217
  • 5
  • 26
  • 46

1 Answers1

3

Get rid of the addFlags() call. None of those are for requesting content. Principally, they are for granting rights to others. For example, you might use FLAG_GRANT_READ_URI_PERMISSION and/or FLAG_GRANT_WRITE_URI_PERMISSION in an ACTION_VIEW Intent, as you are supplying content to another app and need to ensure that it has rights to read and/or write that content.

FLAG_GRANT_PERSISTABLE_URI_PERMISSION and FLAG_GRANT_PREFIX_URI_PERMISSION are used to further describe the permission grant:

  • Can we request that the permissions be saved by the system?
  • Are those permissions just for the associated Uri, or is it for the Uri and any descendants (i.e., where the associated Uri is a prefix)
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491