Skip to content

Commit 9be26e1

Browse files
Fix android detection when python4android is present
Use the builtin mActivity of python4android to get hold of our main activity, which is capable of generating a proper application context.
1 parent 120a441 commit 9be26e1

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

src/platformdirs/android.py

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import re
77
import sys
88
from functools import lru_cache
9-
from typing import cast
9+
from typing import TYPE_CHECKING, cast
1010

1111
from .api import PlatformDirsABC
1212

@@ -119,14 +119,31 @@ def site_runtime_dir(self) -> str:
119119
@lru_cache(maxsize=1)
120120
def _android_folder() -> str | None:
121121
""":return: base folder for the Android OS or None if it cannot be found"""
122-
try:
123-
# First try to get a path to android app via pyjnius
124-
from jnius import autoclass # noqa: PLC0415
125-
126-
context = autoclass("android.content.Context")
127-
result: str | None = context.getFilesDir().getParentFile().getAbsolutePath()
128-
except Exception: # noqa: BLE001
129-
# if fails find an android folder looking a path on the sys.path
122+
result: str | None = None
123+
# type checker isn't happy with our "import android", just don't do this when type checking
124+
# see https://stackoverflow.com/a/61394121
125+
if not TYPE_CHECKING:
126+
try:
127+
# First try to get a path to android app using python4android (if available)...
128+
from android import mActivity # noqa: PLC0415
129+
130+
context = cast("android.content.Context", mActivity.getApplicationContext()) # noqa: F821
131+
result = context.getFilesDir().getParentFile().getAbsolutePath()
132+
except Exception: # noqa: BLE001
133+
result = None
134+
if result is None:
135+
try:
136+
# ...and fall back to using plain pyjnius, if python4android isn't
137+
# available or doesn't deliver any useful result...
138+
from jnius import autoclass # noqa: PLC0415
139+
140+
context = autoclass("android.content.Context")
141+
result = context.getFilesDir().getParentFile().getAbsolutePath()
142+
except Exception: # noqa: BLE001
143+
result = None
144+
if result is None:
145+
# and if that fails, too, find an android folder looking at path on the sys.path
146+
# warning: only works for apps installed under /data, not adopted storage etc.
130147
pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files")
131148
for path in sys.path:
132149
if pattern.match(path):

0 commit comments

Comments
 (0)