如何获得在 Android 设备上写入和读取文件的权限?在此应用程序中,我尝试创建文件夹、文件并向文件写入一行。 该应用程序只是无法启动。当我第一次启动它时,它要求允许写入存储。
在 logcat 中我得到:
02-22 10:23:22.339 29320 29348 I python : PermissionError: [Errno 13] Permission denied: '/storage/emulated/0/folder'
我的代码:
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.utils import platform
from pathlib import Path
class MyApp(App):
def build(self):
text = "1"+App.get_running_app().user_data_dir + '\n'
self.label = Label(text=text)
if platform == "android":
from android.storage import app_storage_path,primary_external_storage_path
from android.permissions import request_permissions, check_permission, Permission
self.label.text += primary_external_storage_path() +'\n'
folder_path = Path(primary_external_storage_path(),"folder")
request_permissions([Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE])
folder_path.mkdir(parents=True, exist_ok=True)
file = Path(folder_path,"file.txt")
else:
file = Path(Path.home(),"file.txt")
with open(file,"w") as tfile:
tfile.write("test test")
return self.label
if __name__ == '__main__':
MyApp().run()
在 buildozer.spec 中我添加:
# (list) Permissions
# (See https://python-for-android.readthedocs.io/en/latest/buildoptions/#build-options-1 for all the supported syntaxes and properties)
android.permissions = android.permission.WRITE_EXTERNAL_STORAGE, android.permission.READ_EXTERNAL_STORAGE, android.permission.INTERNET
使用 android.permissions 删除 PermissionError
if __name__ == '__main__':
from android.permissions import request_permissions, Permission
request_permissions([Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE])
MyApp().run()