|
6 | 6 | import re |
7 | 7 | import sys |
8 | 8 | from functools import lru_cache |
9 | | -from typing import cast |
| 9 | +from typing import TYPE_CHECKING, cast |
10 | 10 |
|
11 | 11 | from .api import PlatformDirsABC |
12 | 12 |
|
@@ -119,14 +119,31 @@ def site_runtime_dir(self) -> str: |
119 | 119 | @lru_cache(maxsize=1) |
120 | 120 | def _android_folder() -> str | None: |
121 | 121 | """: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. |
130 | 147 | pattern = re.compile(r"/data/(data|user/\d+)/(.+)/files") |
131 | 148 | for path in sys.path: |
132 | 149 | if pattern.match(path): |
|
0 commit comments