如何请求访问Kivy中所有文件的权限?

问题描述 投票:0回答:1

我尝试了多种方法使用kivy(JiCsingApp,以保留以前的数据)在文档中创建目录,但不知怎的,似乎没有一个是正确的,我总是收到错误:[Errno 13]权限被拒绝。如果有人能帮助我解决这个问题,我将不胜感激。如果我创建一个简单的文件,我也会收到错误消息。如果我手动授予权限,程序运行不会出错。

Python 来了:

#....
from kivy.utils import platform
from kivy.logger import Logger
from jnius import autoclass
from plyer import storagepath

...

if platform == 'android':
    from android.permissions import request_permissions, Permission, check_permission
    from android.storage import app_storage_path, primary_external_storage_path, secondary_external_storage_path

...

    def build(self):
        self.title = '易經'
        self.theme_cls.theme_style = "Light"
        self.theme_cls.primary_palette = "Black"
        if platform == 'android':
            self.request_android_permissions()
        else:
            self.store = self.get_store()

        return Builder.load_file('oracle.kv')
    
    def request_android_permissions(self):
        permissions = [Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE]
        request_permissions(permissions, self.on_permissions_granted)

    def on_permissions_granted(self, permissions, grants):
        if all(grants):
            self.store = self.get_store()
        else:
            Logger.error("Permissions were not granted.")
            self.exit_app()
    def create_app_directory(self):
        Environment = autoclass('android.os.Environment')
        File = autoclass('java.io.File')

        app_folder = File(Environment.getExternalStorageDirectory(), 'JiCsingApp')
        
        if not app_folder.exists():
            if app_folder.mkdirs():
                print(f"Directory {app_folder.getAbsolutePath()} created")
                return app_folder.getAbsolutePath()
            else:
                raise PermissionError(f"Failed to create directory:{app_folder.getAbsolutePath()}")
        else:
            print(f"Directory {app_folder.getAbsolutePath()} already exists")
            return app_folder.getAbsolutePath()
        
    def get_store(self):
        json_file_path = None
        
        if platform == 'android':
            app_directory = app_storage_path()
            try:
            # Call the method to create app directory
                app_directory = self.create_app_directory()
                print(f"App directory created at: {app_directory}")
            except Exception as e:
                print(f"Encountered error during directory creation: {e}")
            try:
            # Call the method to create app directory
                app_directory = os.path.join(storagepath.get_home_dir(), 'JiCsingApp')
                if not os.path.exists(app_directory):
                    os.mkdir(app_directory)
            except Exception as e:
                print(f"Encountered error during directory creation: {e}")    
            json_file_path = os.path.join(app_directory, 'prophecies.json')
        else:
                # For other platforms (Windows, MacOS, Linux)
            json_file_path = 'prophecies.json'

        Logger.info(f"Using JSON store at: {json_file_path}")
        return JsonStore(json_file_path)
    def on_start(self):
        # Call the initialize_images method when the app starts
        if not self.check_storage_permission():
            self.request_android_permissions()
        self.initialize_images()

    def check_storage_permission(self):
        # Check if the necessary permissions are already granted
        return (check_permission(Permission.WRITE_EXTERNAL_STORAGE) and 
                check_permission(Permission.READ_EXTERNAL_STORAGE))

这是我的 buildozer.spec 文件(据我所知相关部分):

requirements = plyer, jnius, kivy, https://github.com/kivymd/kivymd/archive/master.zip ...

...

# (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.INTERNET, (name=android.permission.WRITE_EXTERNAL_STORAGE;maxSdkVersion=18)
android.permissions = android.permission.INTERNET, android.permission.WRITE_EXTERNAL_STORAGE,android.permission.READ_EXTERNAL_STORAGE, android.permission.MANAGE_EXTERNAL_STORAGE

感谢任何可以提前提供帮助的人!

python android directory permissions kivy
1个回答
0
投票

您的应用程序的文件访问问题可能与 Android 的较新存储策略有关。通过确保您遵循 Android 10+ 的分区存储实践并使用正确的权限(例如 Android 11+ 的 MANAGE_EXTERNAL_STORAGE),您应该能够解决权限被拒绝的错误。

  • 将 Context.getExternalFilesDir() 用于不需要广泛权限的特定于应用程序的目录。
  • 在 Android 11+ 上请求 MANAGE_EXTERNAL_STORAGE 以获取完整的外部存储访问权限。
  • 确保正确请求权限,并指导用户在需要时启用它们。
© www.soinside.com 2019 - 2024. All rights reserved.