Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 702
m33ts4k0z Avatar asked Jul 07 '19 00:07

m33ts4k0z


People also ask

What is permission controller Android?

What is the Android permissions controller? The Android permissions controller is a part of the Android operating system that tells apps what they can and can't access. When you install a new app, the Android permissions controller is what gives you the option to allow or deny permissions for that app.


Video Answer


1 Answers

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)
like image 128
m33ts4k0z Avatar answered Sep 28 '22 09:09

m33ts4k0z