在Android应用中重启后尝试打开文件夹时出现权限错误

时间:2019-07-07 00:16:50

标签: android android-intent android-activity kotlin storage-access-framework

我的应用程序中有一个首选项页面,该页面要求用户提供保存文件的位置。使用Storage Access Framework将该位置作为URI返回,并且我可以使用它在活动之间存储文件。问题是重启电话后,我从sharedPreferences中检索了URI,并且收到了以下消息:

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

以下是启动意图的代码:

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

和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()
    }

这是我尝试重新访问该文件夹的方法:

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)

编辑:我注意到,即使我之后立即调用它,调用contentResolver.persistedUriPermissions总是返回一个空数组。

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

2 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

问题是我需要为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)