Я реализовал обработку разрешений во время выполнения для запроса разрешений WRITE_EXTERNAL_STORAGE и READ_EXTERNAL_STORAGE с помощью модуля Kivy Permission. Однако, несмотря на запрос этих разрешений, приложение не запрашивает у пользователей доступ к хранилищу на устройствах Android и, следовательно, не может получить доступ к назначенному каталогу кэша.
Вот упрощенная версия моего кода. относится к доступу к хранилищу:
Код: Выделить всё
def handle_permission_error():
dialog = MDDialog(title="Permission Error", text="Please grant all required permissions for the app to function properly.")
dialog.size_hint = [.8, .8]
dialog.pos_hint = {'center_x': .5, 'center_y': .5}
dialog.open()
def check_and_request_permissions():
if platform == 'android':
def callback(permission, results):
if all(results):
logging.info("Got all permissions")
else:
logging.warning("Did not get all permissions")
handle_permission_error()
request_permissions([Permission.WRITE_EXTERNAL_STORAGE,
Permission.READ_EXTERNAL_STORAGE,
Permission.ACCESS_COARSE_LOCATION,
Permission.ACCESS_FINE_LOCATION], callback)
logging.info("Checking and requesting permissions...")
else:
logging.warning("Permissions can only be requested on Android platform")
def setup_cache_directory(map_view):
cache_directory = None
if platform == 'android':
check_and_request_permissions()
max_attempts = 3
attempt = 0
while attempt < max_attempts:
# Set up cache directory after permissions are checked
try:
# Construct the path to the parent directory of "Download"
parent_dir = os.path.dirname(os.getenv('EXTERNAL_STORAGE'))
# Specify the name of your desired folder
folder_name = "MyApp"
# Construct the cache directory path
cache_directory = os.path.join(parent_dir, folder_name, 'cache_tiles')
print("Download directory FIRST:", parent_dir)
print("Cache directory FIRST:", cache_directory)
except Exception as e1:
print("Error getting download directory using os module:", e1)
attempt += 1
if attempt < max_attempts:
logging.info("Retrying attempt %d...", attempt)
time.sleep(1)
if cache_directory is None:
logging.error("Failed to access the download directory after multiple attempts.")
handle_permission_error()
elif platform == 'win':
logging.info("We are on the Windows platform")
current_directory = os.getcwd()
cache_directory = os.path.join(current_directory, 'cache_tiles')
logging.info("Cache directory: %s", cache_directory)
try:
os.makedirs(cache_directory, exist_ok=True)
map_view.cache_dir = cache_directory
except Exception as e:
logging.error("Error creating cache directory: %s", e)
cache_directory = None
else:
logging.warning("Platform is not Android or Windows. Unable to determine download folder.")
if cache_directory is not None:
map_view.cache_dir = cache_directory
Я проверил наличие необходимых разрешений объявлены в файле AndroidManifest.xml, и я не получаю никаких ошибок во время выполнения кода.
Что может быть причиной этой проблемы и как я могу гарантировать, что мой Kivy Приложение правильно обращается к внешнему хранилищу для операций чтения и записи на устройствах Android?
Будем очень признательны за любые идеи и предложения. Спасибо!
Подробнее здесь: https://stackoverflow.com/questions/784 ... ivy-garden