Get permanent path to a directory after user picks it with SAF with file picker #8484
|
My end goal is to allow the user to select favorite folders from their device storage (e.g. Music/playlist or Movies/horror) and then display the folder contents in the app. I am using capawesome's file picker to get permission to the folder but I want to persist the path of the user selected folder and also read its contents. Is there any capacitor native way to do this or will I have to write my own plugin for it? I noticed that apps like VLC already support this so it's definitely something that android allows. |
Replies: 1 comment 2 replies
|
Android does not provide a permanent filesystem path for an SAF directory. The durable identifier is the returned The intended pattern is:
For example, in the native Android result callback: val uri = result.data?.data ?: return
val flags = result.data!!.flags and
(Intent.FLAG_GRANT_READ_URI_PERMISSION or
Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
context.contentResolver.takePersistableUriPermission(uri, flags)
val files = DocumentFile
.fromTreeUri(context, uri)
?.listFiles()
.orEmpty()Add the grant flags when creating the picker 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
)
}One important Capawesome detail: its current Android Unless the plugin adds a persistence option, you will need a small native Capacitor plugin, a fork, or an upstream PR that persists the grant and exposes directory enumeration. Also check So VLC is not holding a permanent POSIX path either; it is persisting the SAF tree URI and accessing it through Android's document APIs. |
The File Picker plugin now sets
FLAG_GRANT_PERSISTABLE_URI_PERMISSIONon thepickDirectoryintent (see capawesome-team/capacitor-plugins#928), so the returned tree URI is now persistable. Note thattakePersistableUriPermission()still needs to be called natively by whatever consumes the returned path — the plugin only makes the grant persistable, it doesn't take it for you.