[英]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.