[英]Permission denied while accessing file Android 11
自 API 级别 29 起,Android 具有范围存储策略,可防止直接访问外部存储,即使您的应用具有 READ_EXTERNAL_STORAGE 权限。 相反,您可以使用系统文件选择器,并将文件作为字节数组传递给 Python:
val REQUEST_OPEN = 0
fun myMethod() {
startActivityForResult(
Intent(if (Build.VERSION.SDK_INT >= 19) Intent.ACTION_OPEN_DOCUMENT
else Intent.ACTION_GET_CONTENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
setType("*/*")
}, REQUEST_OPEN)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_OPEN && resultCode == RESULT_OK) {
val uri = data!!.data!!
// For Java, see https://stackoverflow.com/a/10297073
val content = contentResolver.openInputStream(uri)!!.use { it.readBytes() }
myPythonModule.callAttr("process", content)
}
}
然后 Python 函数可以按照您的喜好访问文件内容:
def process(content):
# `content` is already a bytes-like object, but if you need a standard bytes object:
content = bytes(content)
# If you need a file-like object:
import io
content_file = io.BytesIO(content)
# If you need a filename (less efficient):
import tempfile
with tempfile.NamedTemporaryFile() as temp_file:
temp_file.write(content)
filename = temp_file.name # Valid only inside the `with` block.
这将解决您在 API 31 中为 android 11 mate 设置范围存储的问题
除了在程序初始运行时获得这些权限(READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE)之外,还必须在AndroidManifest.xml文件的tag中添加以下代码。
android: requestLegacyExternalStorage = "true"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.