在Android 11中,由于安全性增强措施,从浏览器访问应用程序特定的文件变得更加困难。以下是通过使用Storage Access Framework(SAF)进行访问的两种方法:
1.使用单个文件选择器来获取所需文件的URI:
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = ""
}
startActivityForResult(intent, REQUEST_CODE)
然后在onActivityResult回调中获取该URI:
if (resultCode == Activity.RESULT_OK) {
val uri: Uri? = resultData?.data
if (uri != null) {
// Your code here
}
}
2.使用SAF的document picker来获取权限并访问特定文件:
// Launch the system picker.
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE)
startActivityForResult(intent, REQUEST_CODE)
// Handle the returned tree uri.
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
val treeUri = data?.data ?: return
val documentUri = DocumentsContract.buildDocumentUriUsingTree(
treeUri, DocumentsContract.getTreeDocumentId(treeUri))
// Your code here
}
}
注意:这些方法需要用户授予允许从浏览器访问文件的权限。对于SAF方法,您还需要在AndroidManifest.xml文件中添加以下权限:
尽管这些方法需要额外的代码,但它们提供了可靠的方式访问应用程序特定的文件。