Search code examples
androidandroid-10.0storage-access-framework

Android Q: Can I set the default directory once and save files without file picker?


I have a question about saving files in Android Q. As far as I understand it, if I want to save a file to a public directory and want it to be accessible by other apps I need to use the Storage Access Framework and the Android's file picker. Can I set up the directory where files will be saved once for example in preference screen without having to choose the directory every time a file is saving?

Thanks in advance.


Solution

  • Can I set up the directory where files will be saved once... without having to choose the directory every time a file is saving?

    On Android 5.1+, you can use ACTION_OPEN_DOCUMENT_TREE to allow the user to choose a base directory. From there, you can:

    • Use DocumentFile.fromTreeUri() to get a DocumentFile representing that tree
    • Use that DocumentFile to create a child tree (e.g., directory)
    • Use ContentResolver and takePersistableUriPermission() to have long-term access to your new child tree
    • Use ContentResolver and DocumentFile to put content into that child tree