Search code examples
androidandroid-intentandroid-activitykotlinstorage-access-framework

Permission error when trying to open folder after restart in Android app


I have a preferences page in my app that asks the user for a place to save a file. This place is returned as a URI using Storage Access Framework and I'm able to use it to store files between activites. The problem is that after I restart the phone, I retrieve the URI from the sharedPreferences, and I receive this:

DocumentFile: Failed query: java.lang.SecurityException: Permission Denial: opening provider com.android.externalstorage.ExternalStorageProvider from ProcessRecord (pid=23302, uid=10334) requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs

Here is the code that starts the intent:

 folderPicker = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)        
 folderPicker.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION)
 startActivityForResult(folderPicker, READ_REQUEST_BY_USER)

and the onActivityResult:

    val takeFlags: Int = folderPicker.flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
    activity!!.contentResolver!!.takePersistableUriPermission(uri, takeFlags)
    val sharedPref = PreferenceManager.getDefaultSharedPreferences(activity?.baseContext)
    with (sharedPref.edit()) {
    putString("savePathURI", uri.toString())
    commit()
    }

And this is how I try to reaccess the folder:

var uri = PreferenceManager.getDefaultSharedPreferences(this).getString("savePathURI","")                
var getSelectedDocument = DocumentFile.fromTreeUri(applicationContext, Uri.parse(uri))!!
var params = BridgeParams(applicationContext, links, filesDir.absolutePath, button, getResources(), progressBar3, getSelectedDocument, contentResolver)

EDIT: I noticed that calling contentResolver.persistedUriPermissions always returns an empty array even if I call it right after:

activity!!.contentResolver!!.takePersistableUriPermission(uri, takeFlags)

Solution

  • The problem was that I needed to add additional flags for the ACTION_OPEN_DOCUMENT_TREE:

    folderPicker = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)        
    folderPicker.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(folderPicker, READ_REQUEST_BY_USER)