Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix android detection when python4android is present #277

Merged
merged 10 commits into from
May 15, 2024
35 changes: 26 additions & 9 deletions src/platformdirs/android.py
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@
import re
import sys
from functools import lru_cache
from typing import cast
from typing import TYPE_CHECKING, cast

from .api import PlatformDirsABC

@@ -119,14 +119,31 @@ def site_runtime_dir(self) -> str:
@lru_cache(maxsize=1)
def _android_folder() -> str | None:
""":return: base folder for the Android OS or None if it cannot be found"""
try:
# First try to get a path to android app via pyjnius
from jnius import autoclass # noqa: PLC0415

context = autoclass("android.content.Context")
result: str | None = context.getFilesDir().getParentFile().getAbsolutePath()
except Exception: # noqa: BLE001
# if fails find an android folder looking a path on the sys.path
result: str | None = None
# type checker isn't happy with our "import android", just don't do this when type checking
# see https://stackoverflow.com/a/61394121
if not TYPE_CHECKING:
try:
# First try to get a path to android app using python4android (if available)...
from android import mActivity # noqa: PLC0415

context = cast("android.content.Context", mActivity.getApplicationContext()) # noqa: F821
result = context.getFilesDir().getParentFile().getAbsolutePath()
except Exception: # noqa: BLE001
result = None
if result is None:
try:
# ...and fall back to using plain pyjnius, if python4android isn't
tmolitor-stud-tu marked this conversation as resolved.
Show resolved Hide resolved
# available or doesn't deliver any useful result...
from jnius import autoclass # noqa: PLC0415

context = autoclass("android.content.Context")
result = context.getFilesDir().getParentFile().getAbsolutePath()
except Exception: # noqa: BLE001
result = None
if result is None:
# and if that fails, too, find an android folder looking at path on the sys.path
# warning: only works for apps installed under /data, not adopted storage etc.
pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files")
for path in sys.path:
if pattern.match(path):