Search code examples
androidscoped-storage

How to get persistent folder permission on Android 11?


My app scans for text files in certain directories. User can tap a button to add a directory:

val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivityForResult(intent, RESULT_CODE_DOCUMENT_TREE)

Then I store the URI in the database and use DocumentsContract to scan the directory for files and to read them. On application start I load stored URIs and process them the same way to scan for files.

On Android API 28 the stored URIs work fine. On Android API 30 I get a SecurityException if I try to access any of them after application restart.

Is there a way to make those permissions persistent on modern Android? Or should I implement a completely different approach?


Solution

  • The permission granted for the selected directory lasts until the user's device restarts. To preserve the access, you have to take permission from the user. You can asks for permission in your onActivityResult method See the example below:

    val contentResolver = applicationContext.contentResolver
    
    val takeFlags: Int = Intent.FLAG_GRANT_READ_URI_PERMISSION or
            Intent.FLAG_GRANT_WRITE_URI_PERMISSION
    // Check for the freshest data.
    contentResolver.takePersistableUriPermission(uri, takeFlags)
    

    More details here