Debian Codegraph @

src/briefcase/integrations/android_sdk.py

raw
1 from __future__ import annotations
2
3 import json
4 import os
5 import re
6 import shlex
7 import shutil
8 import subprocess
9 import time
10 from datetime import datetime
11 from pathlib import Path
12
13 from briefcase.config import PEP508_NAME_RE
14 from briefcase.exceptions import (
15 BriefcaseCommandError,
16 IncompatibleToolError,
17 InputDisabled,
18 InvalidDeviceError,
19 MissingToolError,
20 )
21 from briefcase.integrations.base import ManagedTool, ToolCache
22 from briefcase.integrations.java import JDK
23 from briefcase.integrations.subprocess import SubprocessArgT
24
25 DEVICE_NOT_FOUND = re.compile(r"^error: device '[^']*' not found")
26
27
28 def create_avd_validator(emulators):
29 def _validate_avd_name(avd):
30 if not PEP508_NAME_RE.match(avd):
31 raise ValueError(
32 "An emulator name may only contain "
33 "letters, numbers, hyphens and underscores."
34 )
35 elif avd in emulators:
36 raise ValueError(f"An emulator named '{avd}' already exists.")
37 return True
38
39 return _validate_avd_name
40
41
42 class AndroidDeviceNotAuthorized(BriefcaseCommandError):
43 def __init__(self, device):
44 self.device = device
45 super().__init__(
46 f"""
47 The device you have selected ({device}) has not had developer options and
48 USB debugging enabled. These must be enabled before a device can be used as a
49 target for deployment. For details on how to enable Developer Options, visit:
50
51 https://developer.android.com/studio/debug/dev-options#enable
52
53 Once you have enabled these options on your device, you will be able to select
54 this device as a deployment target.
55
56 """
57 )
58
59
60 class AndroidSDK(ManagedTool):
61 name = "android_sdk"
62 full_name = "Android SDK"
63
64 # Latest version for Command-Line Tools download as of May 2025
65 # **Be sure the gradle.rst docs stay in sync with version updates here**
66 SDK_MANAGER_DOWNLOAD_VER = "13114758"
67 SDK_MANAGER_VER = "19.0"
68
69 def __init__(self, tools: ToolCache, root_path: Path):
70 super().__init__(tools=tools)
71 self.dot_android_path = self.tools.home_path / ".android"
72 self.root_path = root_path
73
74 # A wrapper for testing purposes
75 self.sleep = time.sleep
76
77 @property
78 def cmdline_tools_url(self) -> str:
79 """The Android SDK Command-Line Tools URL appropriate for the current machine.
80
81 The SDK largely only supports typical development environments; if a machine is
82 using an unsupported architecture, `sdkmanager` will error while installing the
83 emulator as a dependency of the build-tools. However, for some of the platforms
84 that are unsupported by sdkmanager, users can set up their own SDK install.
85 """
86 try:
87 platform_name = {
88 "Darwin": {
89 "arm64": "mac",
90 "x86_64": "mac",
91 },
92 "Linux": {
93 "x86_64": "linux",
94 },
95 "Windows": {
96 "AMD64": "win",
97 },
98 }[self.tools.host_os][self.tools.host_arch]
99 except KeyError:
100 raise IncompatibleToolError(
101 tool=self.full_name, env_var="ANDROID_HOME"
102 ) from None
103
104 return (
105 f"https://dl.google.com/android/repository/"
106 f"commandlinetools-{platform_name}-{self.SDK_MANAGER_DOWNLOAD_VER}_latest.zip"
107 )
108
109 @property
110 def cmdline_tools_path(self) -> Path:
111 """Version-specific Command-line tools install root directory."""
112 return self.root_path / "cmdline-tools" / self.SDK_MANAGER_VER
113
114 @property
115 def sdkmanager_filename(self) -> str:
116 return "sdkmanager.bat" if self.tools.host_os == "Windows" else "sdkmanager"
117
118 @property
119 def sdkmanager_path(self) -> Path:
120 return self.cmdline_tools_path / "bin" / self.sdkmanager_filename
121
122 @property
123 def adb_path(self) -> Path:
124 adb = "adb.exe" if self.tools.host_os == "Windows" else "adb"
125 return self.root_path / "platform-tools" / adb
126
127 @property
128 def avdmanager_path(self) -> Path:
129 avdmanager = (
130 "avdmanager.bat" if self.tools.host_os == "Windows" else "avdmanager"
131 )
132 return self.cmdline_tools_path / "bin" / avdmanager
133
134 @property
135 def emulator_path(self) -> Path:
136 emulator = "emulator.exe" if self.tools.host_os == "Windows" else "emulator"
137 return self.root_path / "emulator" / emulator
138
139 @property
140 def avd_path(self) -> Path:
141 return self.dot_android_path / "avd"
142
143 def avd_config_filename(self, avd: str) -> Path:
144 return self.avd_path / f"{avd}.avd/config.ini"
145
146 @property
147 def env(self) -> dict[str, str]:
148 return {
149 "ANDROID_HOME": os.fsdecode(self.root_path),
150 "ANDROID_SDK_ROOT": os.fsdecode(self.root_path),
151 "JAVA_HOME": str(self.tools.java.java_home),
152 }
153
154 @property
155 def emulator_abi(self) -> str:
156 """The ABI to use for the Android emulator."""
157 try:
158 return {
159 "Linux": {
160 "x86_64": "x86_64",
161 "aarch64": "arm64-v8a",
162 },
163 "Darwin": {
164 "x86_64": "x86_64",
165 "arm64": "arm64-v8a",
166 },
167 "Windows": {
168 "AMD64": "x86_64",
169 },
170 }[self.tools.host_os][self.tools.host_arch]
171 except KeyError:
172 raise BriefcaseCommandError(
173 "The Android emulator does not currently support "
174 f"{self.tools.host_os} {self.tools.host_arch} hardware."
175 ) from None
176
177 @property
178 def DEFAULT_DEVICE_TYPE(self) -> str:
179 return "pixel"
180
181 @property
182 def DEFAULT_DEVICE_SKIN(self) -> str:
183 return "pixel_7_pro"
184
185 @property
186 def DEFAULT_SYSTEM_IMAGE(self) -> str:
187 return f"system-images;android-31;default;{self.emulator_abi}"
188
189 @classmethod
190 def sdk_path_from_env(cls, tools: ToolCache) -> tuple[str | None, str | None]:
191 """Determine the file path to an Android SDK from the environment.
192
193 Android has historically supported several env vars to set the location of an
194 Android SDK for build tools. The currently preferred source is ANDROID_HOME;
195 however, ANDROID_SDK_ROOT is also supported as a deprecated setting.
196
197 These values must be same if both set; otherwise, Gradle will error.
198
199 :param tools: ToolCache of available tools
200 :returns: Tuple of path to SDK and the env var name that provided that path
201 """
202 android_home = tools.os.environ.get("ANDROID_HOME")
203 android_sdk_root = tools.os.environ.get("ANDROID_SDK_ROOT")
204
205 if android_home:
206 if android_sdk_root and android_sdk_root != android_home:
207 tools.console.warning(
208 f"""
209 *************************************************************************
210 ** WARNING: ANDROID_HOME and ANDROID_SDK_ROOT are inconsistent **
211 *************************************************************************
212
213 The ANDROID_HOME and ANDROID_SDK_ROOT environment variables are set
214 to different paths:
215
216 ANDROID_HOME: {android_home}
217 ANDROID_SDK_ROOT: {android_sdk_root}
218
219 Briefcase will ignore ANDROID_SDK_ROOT and only use the path
220 specified by ANDROID_HOME.
221
222 You should update your environment configuration to either not set
223 ANDROID_SDK_ROOT, or set both environment variables to the same
224 path.
225
226 *************************************************************************
227 """
228 )
229 sdk_root = android_home
230 sdk_source = "ANDROID_HOME"
231 elif android_sdk_root:
232 sdk_root = android_sdk_root
233 sdk_source = "ANDROID_SDK_ROOT"
234 else:
235 sdk_root = None
236 sdk_source = None
237
238 return sdk_root, sdk_source
239
240 @classmethod
241 def verify_install(
242 cls,
243 tools: ToolCache,
244 install: bool = True,
245 **kwargs,
246 ) -> AndroidSDK:
247 """Verify an Android SDK is available.
248
249 The file paths in ANDROID_HOME and ANDROID_SDK_ROOT environment variables will
250 be checked for a valid SDK.
251
252 If those file paths do not contain an SDK, or no file path is provided, an SDK
253 is downloaded.
254
255 :param tools: ToolCache of available tools
256 :param install: Should the tool be installed if it is not found?
257 :returns: A valid Android SDK wrapper. If Android SDK is not available, and was
258 not installed, raises MissingToolError.
259 """
260 # short circuit since already verified and available
261 if hasattr(tools, "android_sdk"):
262 return tools.android_sdk
263
264 JDK.verify(tools=tools, install=install)
265
266 sdk = None
267
268 # Verify externally-managed Android SDK
269 sdk_root_env, sdk_source_env = cls.sdk_path_from_env(tools=tools)
270 if sdk_root_env:
271 tools.console.debug("Evaluating ANDROID_HOME...", prefix=cls.full_name)
272 tools.console.debug(f"{sdk_source_env}={sdk_root_env}")
273 sdk = AndroidSDK(tools=tools, root_path=Path(sdk_root_env))
274
275 if sdk.exists():
276 if sdk_source_env == "ANDROID_SDK_ROOT":
277 tools.console.warning(
278 """
279 *************************************************************************
280 ** WARNING: Using Android SDK from ANDROID_SDK_ROOT **
281 *************************************************************************
282
283 Briefcase is using the Android SDK specified by the ANDROID_SDK_ROOT
284 environment variable.
285
286 Android has deprecated ANDROID_SDK_ROOT in favor of the
287 ANDROID_HOME environment variable.
288
289 Update your environment configuration to set ANDROID_HOME instead of
290 ANDROID_SDK_ROOT to ensure future compatibility.
291
292 *************************************************************************
293 """
294 )
295 elif sdk.cmdline_tools_path.parent.exists():
296 # a cmdline-tools directory exists,
297 # but the required version isn't installed.
298 # Try to install the required version using the 'latest' version.
299 if not sdk.install_cmdline_tools():
300 sdk = None
301 tools.console.warning(
302 f"""
303 *************************************************************************
304 ** WARNING: Incompatible Command-Line Tools Version **
305 *************************************************************************
306
307 The Android SDK specified by {sdk_source_env} at:
308
309 {sdk_root_env}
310
311 does not contain Command-Line Tools version {cls.SDK_MANAGER_VER}. Briefcase
312 requires this version to be installed to use an external Android SDK.
313 Use Android Studio's SDK Manager to install it.
314
315 Briefcase will proceed using its own SDK instance.
316
317 *************************************************************************
318 """
319 )
320 else:
321 tools.console.warning(
322 f"""
323 *************************************************************************
324 ** {f"WARNING: {sdk_source_env} does not point to an Android SDK":67} **
325 *************************************************************************
326
327 The location pointed to by the {sdk_source_env} environment
328 variable:
329
330 {sdk_root_env}
331
332 doesn't appear to contain an Android SDK with the Command-line Tools installed.
333
334 If {sdk_source_env} is an Android SDK, ensure it is the root directory
335 of the Android SDK instance such that
336
337 ${sdk_source_env}{os.sep}{sdk.sdkmanager_path.relative_to(sdk.root_path)}
338
339 is a valid filepath.
340
341 Briefcase will proceed using its own SDK instance.
342
343 *************************************************************************
344 """
345 )
346 sdk = None
347
348 # Verify Briefcase-managed Android SDK
349 if sdk is None:
350 sdk_root_path = tools.base_path / "android_sdk"
351 sdk = AndroidSDK(tools=tools, root_path=sdk_root_path)
352
353 if not sdk.exists():
354 if not install:
355 raise MissingToolError("Android SDK")
356
357 sdk.delete_legacy_sdk_tools()
358
359 if sdk.cmdline_tools_path.parent.exists():
360 tools.console.info("Upgrading Android SDK...", prefix=cls.name)
361 else:
362 tools.console.info(
363 "The Android SDK was not found; downloading and installing...",
364 prefix=cls.name,
365 )
366 tools.console.info(
367 "To use an existing Android SDK instance, specify its root "
368 "directory path in the ANDROID_HOME environment variable."
369 )
370 tools.console.info()
371 sdk.install()
372
373 # Licences must be accepted to use the SDK
374 sdk.verify_license()
375
376 tools.console.debug(f"Using Android SDK at {sdk.root_path}")
377 tools.android_sdk = sdk
378 return sdk
379
380 def exists(self) -> bool:
381 """Confirm that the SDK actually exists.
382
383 Look for the sdkmanager; and, if necessary, confirm that it is executable.
384 """
385 return self.sdkmanager_path.is_file() and (
386 self.tools.host_os == "Windows"
387 or self.tools.os.access(self.sdkmanager_path, self.tools.os.X_OK)
388 )
389
390 @property
391 def managed_install(self) -> bool:
392 """Is the Android SDK install managed by Briefcase?"""
393 # Although the end-user can provide their own SDK, the SDK also
394 # provides a built-in upgrade mechanism. Therefore, all Android SDKs
395 # are managed installs.
396 return True
397
398 def uninstall(self):
399 """The Android SDK is upgraded in-place instead of being reinstalled."""
400
401 def install(self):
402 """Download and install the Android SDK."""
403 cmdline_tools_zip_path = self.tools.file.download(
404 url=self.cmdline_tools_url,
405 download_path=self.tools.base_path,
406 role="Android SDK Command-Line Tools",
407 )
408
409 # The cmdline-tools package *must* be installed as:
410 # <sdk_path>/cmdline-tools/<cmdline-tools version>
411 #
412 # However, the zip file unpacks a top-level folder named `cmdline-tools`.
413 # So, the unpacking process is:
414 #
415 # 1. Make a <sdk_path>/cmdline-tools folder
416 # 2. Unpack the zip file into that folder, creating
417 # <sdk_path>/cmdline-tools/cmdline-tools
418 # 3. Move <sdk_path>/cmdline-tools/cmdline-tools to
419 # <sdk_path>/cmdline-tools/<cmdline-tools version>
420
421 with self.tools.console.wait_bar(
422 f"Installing Android SDK Command-Line Tools {self.SDK_MANAGER_VER}..."
423 ):
424 self.cmdline_tools_path.parent.mkdir(parents=True, exist_ok=True)
425 try:
426 self.tools.file.unpack_archive(
427 cmdline_tools_zip_path, extract_dir=self.cmdline_tools_path.parent
428 )
429 except (shutil.ReadError, EOFError) as e:
430 raise BriefcaseCommandError(
431 f"""\
432 Unable to unpack Android SDK Command-Line Tools ZIP file.
433 The download may have been interrupted or corrupted.
434
435 Delete {cmdline_tools_zip_path} and run briefcase again.
436 """
437 ) from e
438
439 # If there's an existing version of the cmdline tools, delete them.
440 if self.cmdline_tools_path.exists():
441 self.tools.shutil.rmtree(self.cmdline_tools_path)
442
443 # Rename the top level zip content to the final name
444 (self.cmdline_tools_path.parent / "cmdline-tools").rename(
445 self.cmdline_tools_path
446 )
447
448 # Zip file no longer needed once unpacked.
449 cmdline_tools_zip_path.unlink()
450
451 # Python zip unpacking ignores permission metadata.
452 # On non-Windows, we manually fix permissions.
453 if ( # pragma: no branch
454 self.tools.host_os != "Windows"
455 ): # pragma: no-cover-if-is-windows
456 for binpath in (self.cmdline_tools_path / "bin").glob("*"):
457 if not self.tools.os.access(binpath, self.tools.os.X_OK):
458 binpath.chmod(0o755)
459
460 with self.tools.console.wait_bar("Removing older Android SDK packages..."):
461 self.cleanup_old_installs()
462
463 def upgrade(self):
464 """Upgrade the Android SDK."""
465 try:
466 # Using subprocess.run() with no I/O redirection so the user sees
467 # the full output and can send input.
468 self.tools.subprocess.run(
469 [self.sdkmanager_path, "--update"],
470 env=self.env,
471 check=True,
472 stream_output=False,
473 )
474 except subprocess.CalledProcessError as e:
475 raise BriefcaseCommandError(
476 f"""\
477 Error while updating the Android SDK manager. Please run this command and examine
478 its output for errors.
479
480 $ {self.sdkmanager_path} --update
481 """
482 ) from e
483
484 def install_cmdline_tools(self) -> bool:
485 """Attempt to use 'latest' cmdline-tools to install the currently required
486 version of the Command-Line Tools.
487
488 The Briefcase-managed SDK should always have the required version of cmdline-
489 tools installed; however, user-provided SDKs may not have it.
490
491 :returns: True if successfully installed; False otherwise
492 """
493 self.tools.console.info(
494 f"Installing Android Command-Line Tools {self.SDK_MANAGER_VER}...",
495 prefix=self.full_name,
496 )
497 self.tools.console.info(f"Using Android SDK at {self.root_path}")
498 latest_sdkmanager_path = (
499 self.root_path
500 / "cmdline-tools"
501 / "latest"
502 / "bin"
503 / self.sdkmanager_filename
504 )
505 try:
506 self.tools.subprocess.run(
507 [
508 latest_sdkmanager_path,
509 f"cmdline-tools;{self.SDK_MANAGER_VER}",
510 ],
511 check=True,
512 stream_output=False,
513 )
514 except (OSError, subprocess.CalledProcessError) as e:
515 self.tools.console.debug(str(e))
516 self.tools.console.warning(
517 f"Failed to install cmdline-tools;{self.SDK_MANAGER_VER}"
518 )
519 return False
520 return True
521
522 def delete_legacy_sdk_tools(self):
523 """Delete any legacy Android SDK tools that are installed.
524
525 If no versions of the Command-Line Tools are installed but the 'tools' directory
526 exists, the legacy SDK Tools are probably installed. Since they have been
527 deprecated by more recent releases of SDK Manager, delete them and perform a
528 fresh install.
529
530 The Android SDK Tools were deprecated in Sept 2017.
531 """
532 if (
533 not self.cmdline_tools_path.parent.exists()
534 and (self.root_path / "tools").exists()
535 ):
536 self.tools.console.warning(
537 f"""
538 *************************************************************************
539 ** WARNING: Upgrading Android SDK tools **
540 *************************************************************************
541
542 Briefcase needs to replace the older Android SDK Tools with the
543 newer Android SDK Command-Line Tools. This will involve some large
544 downloads, as well as re-accepting the licenses for the Android
545 SDKs.
546
547 Any emulators created with the older Android SDK Tools will not be
548 compatible with the new tools. You will need to create new
549 emulators. Old emulators can be removed by deleting the files
550 in {self.avd_path} matching the emulator name.
551
552 *************************************************************************
553 """
554 )
555 self.tools.shutil.rmtree(self.root_path)
556
557 def cleanup_old_installs(self):
558 """Remove old versions of Android SDK packages and version markers.
559
560 When the Android SDK is upgraded, old versions of packages should be removed to
561 keep the SDK tidy. This is namely the Command-line Tools that are used to manage
562 the SDK and AVDs. Additionally, previous version of Briefcase created a version
563 marker file that needs to be deleted.
564 """
565 if (ver_file := self.cmdline_tools_path.parent / "8092744").is_file():
566 self.tools.os.unlink(ver_file)
567 if (latest := self.cmdline_tools_path.parent / "latest").is_dir():
568 self.tools.shutil.rmtree(latest)
569
570 def list_packages(self):
571 """In debug output, list the packages currently managed by the SDK."""
572 try:
573 # check_output always writes its output to debug
574 self.tools.subprocess.check_output(
575 [self.sdkmanager_path, "--list_installed"],
576 env=self.env,
577 )
578 except subprocess.CalledProcessError as e:
579 raise BriefcaseCommandError(
580 "Unable to invoke the Android SDK manager"
581 ) from e
582
583 def adb(self, device: str) -> ADB:
584 """Obtain an ADB instance for managing a specific device.
585
586 :param device: The device ID to manage.
587 """
588 return ADB(tools=self.tools, device=device)
589
590 def verify_license(self):
591 """Verify that all necessary licenses have been accepted.
592
593 If they haven't, prompt the user to do so.
594
595 Raises an error if licenses are not.
596 """
597 license_path = self.root_path / "licenses/android-sdk-license"
598 if license_path.exists():
599 return
600
601 self.tools.console.info(
602 """
603 The Android tools provided by Google have license terms that you must accept
604 before you may use those tools.
605 """
606 )
607 try:
608 # Using subprocess.run() with no I/O redirection so the user sees
609 # the full output and can send input.
610 self.tools.subprocess.run(
611 [self.sdkmanager_path, "--licenses"],
612 env=self.env,
613 check=True,
614 stream_output=False,
615 )
616 except (subprocess.CalledProcessError, OSError) as e:
617 raise BriefcaseCommandError(
618 f"""\
619 Error while reviewing Android SDK licenses. Please run this command and examine
620 its output for errors.
621
622 $ {self.sdkmanager_path} --licenses
623 """
624 ) from e
625
626 if not license_path.exists():
627 raise BriefcaseCommandError(
628 """\
629 You did not accept the Android SDK licenses. Please re-run the briefcase command
630 and accept the Android SDK license when prompted. You may need an Internet
631 connection.
632 """
633 )
634
635 def verify_emulator(self):
636 """Verify that Android emulator has been installed, and is in a runnable state.
637
638 Raises an error if the emulator can't be installed.
639 """
640 # Ensure the `platforms` folder exists.
641 # See the discussion on #766 for details; as of June 2022, if this folder
642 # doesn't exist, the emulator won't start, raising the error:
643 #
644 # PANIC: Cannot find AVD system path. Please define ANDROID_SDK_ROOT
645 #
646 # Creating an empty platforms folder is enough to overcome this. This folder
647 # will be created automatically when you build a project; but if you have a
648 # clean Android SDK install that hasn't been used to build a project, it
649 # might be missing.
650 (self.root_path / "platforms").mkdir(exist_ok=True)
651
652 if self.emulator_path.exists():
653 self.tools.console.debug("Android emulator is already installed.")
654 return
655
656 self.tools.console.info("Downloading the Android emulator...")
657 try:
658 self.tools.subprocess.run(
659 [self.sdkmanager_path, "platform-tools", "emulator"],
660 env=self.env,
661 check=True,
662 stream_output=False,
663 )
664 except subprocess.CalledProcessError as e:
665 raise BriefcaseCommandError(
666 "Error while installing Android emulator."
667 ) from e
668
669 def verify_avd(self, avd: str):
670 """Verify that the AVD has the necessary system components to launch.
671
672 This includes:
673 * AVD system image
674 * Emulator skin
675
676 :param avd: The AVD name to verify.
677 """
678 # Read the AVD configuration to retrieve the system image.
679 # This is stored in the AVD configuration file with the key:
680 # image.sysdir.1=system-images/android-31/default/arm64-v8a/
681 avd_config = self.avd_config(avd)
682
683 try:
684 system_image_path = Path(avd_config["image.sysdir.1"])
685
686 # Convert the path into a system image name, and verify it.
687 self.verify_system_image(";".join(system_image_path.parts))
688 except KeyError:
689 self.tools.console.warning(
690 f"""
691 *************************************************************************
692 ** WARNING: Unable to determine AVD system image **
693 *************************************************************************
694
695 Briefcase was unable to determine the system image of the Android
696 emulator AVD {avd!r} from it's configuration file.
697
698 Briefcase will proceed assuming the emulator is correctly
699 configured. If you experience any problems running the emulator,
700 this may be the cause of the problem.
701
702 *************************************************************************
703 """
704 )
705
706 try:
707 skin = avd_config["skin.name"]
708 skin_path = Path(avd_config["skin.path"])
709 if skin_path == Path("_no_skin"):
710 self.tools.console.debug("Emulator does not use a skin.")
711 elif skin_path != Path("skins") / skin:
712 self.tools.console.warning(
713 f"""
714 *************************************************************************
715 ** WARNING: Unrecognized device skin **
716 *************************************************************************
717
718 Briefcase does not recognize the skin {skin!r} used by the
719 Android emulator AVD {avd!r}.
720
721 Briefcase will proceed assuming the emulator is correctly
722 configured. If you experience any problems running the emulator,
723 this may be the cause of the problem.
724
725 *************************************************************************
726 """
727 )
728 else:
729 # Convert the path into a system image name, and verify it.
730 self.verify_emulator_skin(skin)
731
732 except KeyError:
733 self.tools.console.debug(f"Device {avd!r} doesn't define a skin.")
734
735 def verify_system_image(self, system_image: str):
736 """Verify that the required system image is installed.
737
738 :param system_image: The SDKManager identifier for the system image (e.g.,
739 ``"system-images;android-31;default;x86_64"``)
740 """
741 # Look for the directory named as a system image.
742 # If it exists, we already have the system image.
743 system_image_parts = system_image.split(";")
744
745 if len(system_image_parts) < 4 or system_image_parts[0] != "system-images":
746 raise BriefcaseCommandError(
747 f"{system_image!r} is not a valid system image name."
748 )
749
750 if system_image_parts[-1] != self.emulator_abi:
751 self.tools.console.warning(
752 f"""
753 *************************************************************************
754 ** WARNING: Unexpected emulator ABI **
755 *************************************************************************
756
757 The system image {system_image!r}
758 does not match the architecture of this computer ({self.emulator_abi}).
759
760 Briefcase will proceed assuming the emulator is correctly
761 configured. If you experience any problems running the emulator,
762 this may be the cause of the problem.
763
764 *************************************************************************
765 """
766 )
767
768 # Convert the system image into a path where that system image
769 # would be expected, and see if the location exists.
770 system_image_path = self.root_path
771 for part in system_image_parts:
772 system_image_path = system_image_path / part
773
774 if system_image_path.exists():
775 # Found the system image.
776 return
777
778 # System image not found; download it.
779 self.tools.console.info(
780 f"Downloading the {system_image!r} Android system image...",
781 prefix=self.name,
782 )
783 try:
784 self.tools.subprocess.run(
785 [self.sdkmanager_path, system_image],
786 env=self.env,
787 check=True,
788 stream_output=False,
789 )
790 except subprocess.CalledProcessError as e:
791 raise BriefcaseCommandError(
792 f"Error while installing the {system_image!r} Android system image."
793 ) from e
794
795 def verify_emulator_skin(self, skin: str):
796 """Verify that an emulator skin is available.
797
798 A human-readable list of available skins can be found here:
799
800 https://android.googlesource.com/platform/tools/adt/idea/+/refs/heads/mirror-goog-studio-main/artwork/resources/device-art-resources/
801
802 :param skin: The name of the skin to obtain
803 """
804 # Check for a device skin. If it doesn't exist, download it.
805 skin_path = self.root_path / "skins" / skin
806 if skin_path.exists():
807 self.tools.console.debug(f"Device skin {skin!r} already exists.")
808 return
809
810 self.tools.console.info(f"Obtaining {skin} device skin...", prefix=self.name)
811
812 skin_url = (
813 "https://android.googlesource.com/platform/tools/adt/idea/"
814 "+archive/refs/heads/mirror-goog-studio-main/"
815 f"artwork/resources/device-art-resources/{skin}.tar.gz"
816 )
817
818 skin_tgz_path = self.tools.file.download(
819 url=skin_url,
820 download_path=self.root_path,
821 role=f"{skin} device skin",
822 )
823
824 # Unpack skin archive
825 with self.tools.console.wait_bar("Installing device skin..."):
826 try:
827 self.tools.file.unpack_archive(
828 skin_tgz_path,
829 extract_dir=skin_path,
830 )
831 except (shutil.ReadError, EOFError) as e:
832 raise BriefcaseCommandError(
833 f"Unable to unpack {skin} device skin."
834 ) from e
835
836 # Delete the downloaded file.
837 skin_tgz_path.unlink()
838
839 def emulators(self) -> list[str]:
840 """Find the list of emulators that are available."""
841 try:
842 emulators = self.tools.subprocess.check_output(
843 [self.emulator_path, "-list-avds"]
844 ).strip()
845 except subprocess.CalledProcessError as e:
846 raise BriefcaseCommandError("Unable to obtain Android emulator list") from e
847 else:
848 return [
849 emu
850 for emu in emulators.split("\n")
851 # ignore any logging output included in output list
852 if emu and not emu.startswith(("INFO |", "WARNING |", "ERROR |"))
853 ]
854
855 def devices(self) -> dict[str, dict[str, str | bool]]:
856 """Find the devices that are attached and available to ADB."""
857 try:
858 output = self.tools.subprocess.check_output(
859 [self.adb_path, "devices", "-l"]
860 ).strip()
861 # Process the output of `adb devices -l`.
862 # The first line is header information.
863 # Each subsequent line is a single device descriptor.
864 devices = {}
865 header_found = False
866 for line in output.split("\n"):
867 if line == "List of devices attached":
868 header_found = True
869 elif header_found and line:
870 parts = re.sub(r"\s+", " ", line).split(" ")
871
872 details = {}
873 for part in parts[2:]:
874 try:
875 key, value = part.split(":")
876 details[key] = value
877 except ValueError:
878 # Ignore any entry that isn't in "key:value" format.
879 pass
880
881 if parts[1] == "device":
882 try:
883 name = details["model"].replace("_", " ")
884 except KeyError:
885 name = "Unknown device (no model name)"
886 authorized = True
887 elif parts[1] == "offline":
888 name = "Unknown device (offline)"
889 authorized = False
890 else:
891 name = (
892 f"Device not available for development "
893 f"({' '.join(parts[1:])})"
894 )
895 authorized = False
896
897 devices[parts[0]] = {
898 "name": name,
899 "authorized": authorized,
900 }
901
902 return devices
903 except subprocess.CalledProcessError as e:
904 raise BriefcaseCommandError("Unable to obtain Android device list") from e
905
906 def select_target_device(
907 self,
908 device_or_avd: str | None,
909 ) -> tuple[str | None, str | None, str | None]:
910 """Select a device to be the target for actions.
911
912 Interrogates the system to get the list of available devices.
913
914 If the user has specified a device at the command line, that device will
915 be validated, and then automatically selected.
916
917 :param device_or_avd: The device or AVD to target. Can be a physical
918 device id (a hex string), an emulator id (``emulator-5554``), or an
919 emulator AVD name (``@robotfriend``), or a JSON payload describing
920 the properties of an emulator that will be created (e.g.,
921 ``'{"avd":"beePhone","device_type":"pixel","skin":"pixel_3a","system_image":"system-images;android-31;default;arm64-v8a"}'``)
922 If ``None``, the user will be asked to select a device from the list
923 available.
924 :returns: A tuple containing ``(device, name, avd)``. ``avd`` will only
925 be provided if an emulator with that AVD is not currently running.
926 If ``device`` is None, a new emulator should be created.
927 """
928 # If the device_or_avd starts with "{", it's a definition for a new
929 # emulator to be created.
930 if device_or_avd and device_or_avd.startswith("{"):
931 try:
932 emulator_config = json.loads(device_or_avd)
933 emulators = set(self.emulators())
934
935 # If an emulator with this AVD already exists, use it
936 avd = emulator_config["avd"]
937 if avd not in emulators:
938 self._create_emulator(**emulator_config)
939
940 return None, f"@{avd} (emulator)", avd
941 except json.JSONDecodeError as e:
942 raise BriefcaseCommandError(
943 f"Unable to create emulator with definition {device_or_avd!r}"
944 ) from e
945 except KeyError:
946 raise BriefcaseCommandError("No AVD provided for new device.") from None
947 except TypeError as e:
948 property = str(e).split(" ")[-1]
949 raise BriefcaseCommandError(
950 f"Unknown device property {property}."
951 ) from None
952
953 # Get the list of attached devices (includes running emulators)
954 running_devices = self.devices()
955
956 # Choices is an ordered list of options that can be shown to the user.
957 # Each device should appear only once, and be keyed by AVD only if
958 # a device ID isn't available.
959 choices = {}
960 # A full index of available devices. Devices can be looked up by any valid key -
961 # ID *or* AVD.
962 device_index = {}
963
964 # Iterate over all the running devices.
965 # If the device is a virtual device, use ADB to get the emulator AVD name.
966 # If it is a physical device, use the device name.
967 # Keep a log of all running AVDs
968 running_avds = {}
969 for d, details in sorted(running_devices.items(), key=lambda d: d[1]["name"]):
970 name = details["name"]
971 avd = self.adb(d).avd_name()
972 if avd:
973 # It's a running emulator
974 running_avds[avd] = d
975 full_name = f"@{avd} (running emulator)"
976 choices[d] = full_name
977
978 # Save the AVD as a device detail.
979 details["avd"] = avd
980
981 # Device can be looked up by device ID or AVD
982 device_index[d] = full_name
983 device_index[f"@{avd}"] = full_name
984 else:
985 # It's a physical device (might be disabled)
986 full_name = f"{name} ({d})"
987 choices[d] = full_name
988 device_index[d] = full_name
989
990 # Add any non-running emulator AVDs to the list of candidate devices
991 for avd in self.emulators():
992 if avd not in running_avds:
993 name = f"@{avd} (emulator)"
994 choices[f"@{avd}"] = name
995 device_index[f"@{avd}"] = name
996
997 # If a device or AVD has been provided, check it against the available
998 # device list.
999 if device_or_avd:
1000 try:
1001 name = device_index[device_or_avd]
1002
1003 if device_or_avd.startswith("@"):
1004 # specifier is an AVD
1005 avd = device_or_avd[1:]
1006 try:
1007 device = running_avds[avd]
1008 except KeyError:
1009 # device_or_avd isn't in the list of running avds;
1010 # it must be a non-running emulator.
1011 return None, name, avd
1012 else:
1013 # Specifier is a direct device ID
1014 device = device_or_avd
1015
1016 details = running_devices[device]
1017 avd = details.get("avd")
1018 if details["authorized"]:
1019 # An authorized, running device (emulator or physical)
1020 return device, name, avd
1021 else:
1022 # An unauthorized physical device
1023 raise AndroidDeviceNotAuthorized(device)
1024
1025 except KeyError as e:
1026 # Provided device_or_id isn't a valid device identifier.
1027 id_type = (
1028 "emulator AVD" if device_or_avd.startswith("@") else "device ID"
1029 )
1030 raise InvalidDeviceError(id_type, device_or_avd) from e
1031 # We weren't given a device/AVD; we have to select from the list.
1032 # If we're selecting from a list, there's always one last choice
1033 choices["-"] = "Create a new Android emulator"
1034
1035 # Show the choices to the user.
1036 try:
1037 choice = self.tools.console.selection_question(
1038 intro="Select Android device to use:",
1039 description="Android device",
1040 options=choices,
1041 )
1042 except InputDisabled as e:
1043 # If input is disabled, and there's only one actual simulator,
1044 # select it. If there are no simulators, select "Create simulator"
1045 if len(choices) <= 2:
1046 choice = next(iter(choices))
1047 else:
1048 raise BriefcaseCommandError(
1049 """\
1050 Input has been disabled; can't select a device to target.
1051 Use the -d/--device option to explicitly specify the device to use.
1052 """
1053 ) from e
1054
1055 # Process the user's choice
1056 if choice == "-":
1057 # Create a new emulator. No device ID or AVD.
1058 device = None
1059 avd = None
1060 name = None
1061 elif choice.startswith("@"):
1062 # A non-running emulator. We have an AVD, but no device ID.
1063 device = None
1064 name = device_index[choice]
1065 avd = choice[1:]
1066 else:
1067 # Either a running emulator, or a physical device. Regardless,
1068 # we need to check if the device is developer enabled.
1069 # Functionally, we know the device *must* be in the list of
1070 # choices; which means it's also in the list of running devices
1071 # and the list of device choices, so any KeyError on those lookups
1072 # indicates a deeper problem.
1073 details = running_devices[choice]
1074 if not details["authorized"]:
1075 # An unauthorized physical device
1076 raise AndroidDeviceNotAuthorized(choice)
1077
1078 # Return the device ID and name.
1079 device = choice
1080 name = device_index[choice]
1081 avd = details.get("avd")
1082
1083 if avd:
1084 self.tools.console.info(
1085 f"""
1086 In future, you can specify this device by running:
1087
1088 $ briefcase run android -d "@{avd}"
1089 """
1090 )
1091 elif device:
1092 self.tools.console.info(
1093 f"""
1094 In future, you can specify this device by running:
1095
1096 $ briefcase run android -d {device}
1097 """
1098 )
1099
1100 return device, name, avd
1101
1102 def create_emulator(self) -> str:
1103 """Create a new Android emulator.
1104
1105 :returns: The AVD of the newly created emulator.
1106 """
1107 # Get the list of existing emulators
1108 emulators = set(self.emulators())
1109
1110 default_avd = "beePhone"
1111 i = 1
1112 # Make sure the default name is unique
1113 while default_avd in emulators:
1114 i += 1
1115 default_avd = f"beePhone{i}"
1116
1117 # Prompt for a device avd until a valid one is provided.
1118 avd = self.tools.console.text_question(
1119 intro=f"""\
1120 You need to select a name for your new emulator. This is an identifier that
1121 can be used to start the emulator in future. It should follow the same naming
1122 conventions as a Python package (i.e., it may only contain letters, numbers,
1123 hyphens and underscores). If you don't provide a name, Briefcase will use the
1124 a default name '{default_avd}'.
1125 """,
1126 description="Emulator Name",
1127 default=default_avd,
1128 validator=create_avd_validator(emulators),
1129 )
1130
1131 # TODO: Provide a list of options for device types with matching skins
1132 device_type = self.DEFAULT_DEVICE_TYPE
1133 skin = self.DEFAULT_DEVICE_SKIN
1134
1135 # TODO: Provide a list of options for system images.
1136 system_image = self.DEFAULT_SYSTEM_IMAGE
1137
1138 self._create_emulator(
1139 avd=avd,
1140 device_type=device_type,
1141 skin=skin,
1142 system_image=system_image,
1143 )
1144
1145 self.tools.console.info(
1146 f"""
1147 Android emulator '{avd}' created.
1148
1149 In future, you can specify this device by running:
1150
1151 $ briefcase run android -d @{avd}
1152 """
1153 )
1154
1155 return avd
1156
1157 def _create_emulator(
1158 self,
1159 avd: str,
1160 device_type: str | None = None,
1161 skin: str | None = None,
1162 system_image: str | None = None,
1163 ):
1164 """Internal method that does the actual work of creating the emulator.
1165
1166 AVD is the only required argument; all other arguments will assume reasonable
1167 defaults.
1168
1169 :param avd: The AVD for the new emulator
1170 :param device_type: The device type for the new emulator (e.g., "pixel")
1171 :param skin: The skin for the new emulator to use (e.g., "pixel_3a")
1172 :param system_image: The system image to use on the new emulator. (e.g.,
1173 "system-images;android-31;default;arm64-v8a")
1174 """
1175 if device_type is None:
1176 device_type = self.DEFAULT_DEVICE_TYPE
1177 if skin is None:
1178 skin = self.DEFAULT_DEVICE_SKIN
1179 if system_image is None:
1180 system_image = self.DEFAULT_SYSTEM_IMAGE
1181
1182 # Ensure the required skin is available.
1183 self.verify_emulator_skin(skin)
1184
1185 # Ensure the required system image is available.
1186 self.verify_system_image(system_image)
1187
1188 with self.tools.console.wait_bar(f"Creating Android emulator {avd}..."):
1189 try:
1190 self.tools.subprocess.check_output(
1191 [
1192 self.avdmanager_path,
1193 "--verbose",
1194 "create",
1195 "avd",
1196 "--name",
1197 avd,
1198 "--abi",
1199 self.emulator_abi,
1200 "--package",
1201 system_image,
1202 "--device",
1203 device_type,
1204 ],
1205 # Ensure XDG_CONFIG_HOME is not set so avdmanager uses the default
1206 # location (i.e. ~/.android) because the emulator does not respect
1207 # XDG_CONFIG_HOME and will not be able to find the AVD to run it.
1208 env={
1209 **self.env,
1210 "XDG_CONFIG_HOME": None,
1211 },
1212 )
1213 except subprocess.CalledProcessError as e:
1214 raise BriefcaseCommandError("Unable to create Android emulator") from e
1215
1216 with self.tools.console.wait_bar("Adding extra device configuration..."):
1217 self.update_emulator_config(
1218 avd,
1219 {
1220 "avd.id": avd,
1221 "avd.name": avd,
1222 "disk.dataPartition.size": "4096M",
1223 "hw.keyboard": "yes",
1224 "skin.dynamic": "yes",
1225 "skin.name": skin,
1226 "skin.path": f"skins/{skin}",
1227 "showDeviceFrame": "yes",
1228 },
1229 )
1230
1231 def avd_config(self, avd: str) -> dict[str, str]:
1232 """Obtain the AVD configuration as key-value pairs.
1233
1234 :params avd: The AVD whose config will be retrieved
1235 """
1236 # Parse the existing config into key-value pairs
1237 avd_config = {}
1238 try:
1239 with self.avd_config_filename(avd).open("r", encoding="utf-8") as f:
1240 for line in f:
1241 try:
1242 key, value = line.rstrip().split("=", 1)
1243 avd_config[key.strip()] = value.strip()
1244 except ValueError:
1245 pass
1246 except OSError as e:
1247 raise BriefcaseCommandError(
1248 f"Unable to read configuration of AVD @{avd}"
1249 ) from e
1250
1251 return avd_config
1252
1253 def update_emulator_config(self, avd: str, updates: dict[str, str]):
1254 """Update the AVD configuration with specific values.
1255
1256 :params avd: The AVD whose config will be updated
1257 :params updates: A dictionary containing the new key-value to add to the device
1258 configuration.
1259 """
1260 avd_config = self.avd_config(avd)
1261
1262 # Augment the config with the new key-values pairs
1263 avd_config.update(updates)
1264
1265 # Write the update configuration.
1266 with self.avd_config_filename(avd).open("w", encoding="utf-8") as f:
1267 for key, value in avd_config.items():
1268 f.write(f"{key}={value}\n")
1269
1270 def start_emulator(
1271 self,
1272 avd: str,
1273 extra_args: list[str] | None = None,
1274 ) -> tuple[str, str]:
1275 """Start an existing Android emulator.
1276
1277 Returns when the emulator is booted and ready to accept apps.
1278
1279 :param avd: The AVD of the device.
1280 :param extra_args: Additional command line arguments to pass when starting the
1281 emulator.
1282 """
1283 if avd not in set(self.emulators()):
1284 raise InvalidDeviceError("emulator AVD", avd)
1285
1286 if extra_args is None:
1287 extra_args = []
1288
1289 # Start the emulator
1290 emulator_popen = self.tools.subprocess.Popen(
1291 [self.emulator_path, f"@{avd}", "-dns-server", "8.8.8.8", *extra_args],
1292 env=self.env,
1293 stdout=subprocess.PIPE,
1294 stderr=subprocess.STDOUT,
1295 bufsize=1,
1296 start_new_session=True,
1297 )
1298
1299 # Start capturing the emulator's output
1300 # On Windows, the emulator can block until stdout is read and the emulator will
1301 # not actually run until the user sends CTRL+C to Briefcase (#1573). This
1302 # avoids that scenario while also ensuring emulator output is always available
1303 # to print in the console if other issues occur.
1304 emulator_streamer = self.tools.subprocess.stream_output_non_blocking(
1305 label="Android emulator",
1306 popen_process=emulator_popen,
1307 capture_output=True,
1308 )
1309
1310 # wrap AVD name in quotes since '@' is a special char in PowerShell
1311 emulator_command = " ".join(
1312 f'"{arg}"' if arg.startswith("@") else arg
1313 for arg in map(str, emulator_popen.args)
1314 )
1315
1316 general_error_msg = f"""
1317 Review the emulator output above for:
1318 - Troubleshooting or resolution steps such as enabling hardware acceleration
1319 - Other errors or warnings that may be suggesting the cause of the startup failure
1320
1321 Ensure your Android SDK is up-to-date by running:
1322
1323 $ briefcase upgrade {AndroidSDK.name}
1324
1325 To review Google's general troubleshooting steps for the emulator, visit:
1326
1327 https://developer.android.com/studio/run/emulator-troubleshooting
1328
1329 You can also start the emulator manually by running:
1330
1331 $ {emulator_command}
1332 """
1333
1334 failed_startup_error_msg = f"{{prologue}}\n{general_error_msg}"
1335
1336 # The boot process happens in 2 phases.
1337 # First, the emulator appears in the device list. However, it's not ready until
1338 # the boot process has finished. To determine the boot status, we need the
1339 # device ID, and an ADB connection.
1340
1341 # Phase 1: Wait for the device to appear so we can get an ADB instance for it.
1342 try:
1343 with self.tools.console.wait_bar("Starting emulator...") as keep_alive:
1344 adb = None
1345 known_devices = set()
1346 while adb is None:
1347 if emulator_popen.poll() is not None:
1348 raise BriefcaseCommandError(
1349 failed_startup_error_msg.format(
1350 prologue="Android emulator was unable to start!"
1351 )
1352 )
1353
1354 for device, details in sorted(self.devices().items()):
1355 # Only process authorized devices that we haven't seen.
1356 if details["authorized"] and device not in known_devices:
1357 adb = self.adb(device)
1358 device_avd = adb.avd_name()
1359
1360 if device_avd == avd:
1361 # Found an active device that matches
1362 # the AVD we are starting.
1363 full_name = f"@{avd} (running emulator)"
1364 break
1365 else:
1366 # Not the one. Zathras knows.
1367 adb = None
1368 known_devices.add(device)
1369
1370 # If we haven't found a device, try again in 2 seconds...
1371 if adb is None:
1372 keep_alive.update()
1373 self.sleep(2)
1374
1375 # Phase 2: Wait for the boot process to complete
1376 if not adb.has_booted():
1377 with self.tools.console.wait_bar("Booting emulator...") as keep_alive:
1378 while not adb.has_booted():
1379 if emulator_popen.poll() is not None:
1380 raise BriefcaseCommandError(
1381 failed_startup_error_msg.format(
1382 prologue="Android emulator was unable to boot!"
1383 )
1384 )
1385
1386 # Try again in 2 seconds...
1387 keep_alive.update()
1388 self.sleep(2)
1389 except BaseException as e:
1390 self.tools.console.warning(
1391 "Emulator output log for startup failure",
1392 prefix=self.name,
1393 )
1394 self.tools.console.info(emulator_streamer.captured_output)
1395
1396 # Provide troubleshooting steps if user gives up on the emulator starting
1397 if isinstance(e, KeyboardInterrupt):
1398 self.tools.console.warning(
1399 "Is the Android emulator not starting up properly?",
1400 prefix=self.name,
1401 )
1402 self.tools.console.info(
1403 """
1404 If the emulator opened after pressing CTRL+C, then leave the emulator open and
1405 run Briefcase again. The running emulator can then be selected from the list.
1406 """
1407 )
1408 self.tools.console.info(general_error_msg)
1409
1410 raise
1411 finally:
1412 emulator_streamer.request_stop()
1413
1414 # Return the device ID and full name.
1415 return device, full_name
1416
1417
1418 class ADB:
1419 def __init__(self, tools: ToolCache, device: str):
1420 """An API integration for the Android Debug Bridge (ADB).
1421
1422 :param tools: ToolCache of available tools
1423 :param device: The ID of the device to target (in a format usable by `adb -s`)
1424 """
1425 self.tools = tools
1426 self.device = device
1427
1428 def avd_name(self) -> str | None:
1429 """Get the AVD name for the device.
1430
1431 :returns: The AVD name for the device; or ``None`` if the device isn't
1432 an emulator
1433 """
1434 try:
1435 output = self.run("emu", "avd", "name", quiet=1)
1436 return output.split("\n")[0]
1437 except subprocess.CalledProcessError as e:
1438 # Status code 1 is a normal "it's not an emulator" error response
1439 if e.returncode == 1:
1440 return None
1441 else:
1442 raise BriefcaseCommandError(
1443 f"Unable to interrogate AVD name of device {self.device}"
1444 ) from e
1445
1446 def has_booted(self) -> bool:
1447 """Determine if the device has completed booting.
1448
1449 :returns: True if it has booted; False otherwise.
1450 """
1451 try:
1452 # When the sys.boot_completed property of the device
1453 # returns '1', the boot is complete. Any other response indicates
1454 # booting is underway.
1455 output = self.run("shell", "getprop", "sys.boot_completed")
1456 return output.strip() == "1"
1457 except subprocess.CalledProcessError as e:
1458 raise BriefcaseCommandError(
1459 f"Unable to determine if emulator {self.device} has booted."
1460 ) from e
1461
1462 def run(self, *arguments: SubprocessArgT, quiet: int = 0) -> str:
1463 """Run a command on a device using Android debug bridge, `adb`. The device name
1464 is mandatory to ensure clarity in the case of multiple attached devices.
1465
1466 :param arguments: List of strings to pass to `adb` as arguments.
1467 :param quiet: Should the invocation of this command be silent, and
1468 *not* appear in the logs? This should almost always be 0;
1469 however, for some calls (most notably, calls that are called
1470 frequently to evaluate the status of another process), logging can
1471 be turned off so that log output isn't corrupted by thousands of
1472 polling calls.
1473 :returns: `adb` output on success; raises an exception on failure.
1474 """
1475 # The ADB integration operates on the basis of running commands before
1476 # checking that they are valid, then parsing output to notice errors.
1477 # This keeps performance good in the success case.
1478 try:
1479 output = self.tools.subprocess.check_output(
1480 [self.tools.android_sdk.adb_path, "-s", self.device, *arguments],
1481 quiet=quiet,
1482 )
1483 # add returns status code 0 in the case of failure.
1484 # The only tangible evidence of failure is the message
1485 # "Failure [INSTALL_FAILED_OLDER_SDK]" in the console output;
1486 # so if that message exists in the output, raise an exception.
1487 if "Failure [INSTALL_FAILED_OLDER_SDK]" in output:
1488 raise BriefcaseCommandError(
1489 "Your device doesn't meet the minimum SDK requirements of this app."
1490 )
1491 return output
1492 except subprocess.CalledProcessError as e:
1493 if any(DEVICE_NOT_FOUND.match(line) for line in e.output.split("\n")):
1494 raise InvalidDeviceError("device id", self.device) from e
1495 raise
1496
1497 def install_apk(self, apk_path: str | Path):
1498 """Install an APK file on an Android device.
1499
1500 :param apk_path: The path of the Android APK file to install.
1501 :returns: `None` on success; raises an exception on failure.
1502 """
1503 try:
1504 self.run("install", "-r", apk_path)
1505 except subprocess.CalledProcessError as e:
1506 raise BriefcaseCommandError(
1507 f"Unable to install APK {apk_path} on {self.device}"
1508 ) from e
1509
1510 def force_stop_app(self, package: str):
1511 """Force-stop an app, specified as a package name.
1512
1513 :param package: The name of the Android package, e.g., com.username.myapp.
1514 :returns: `None` on success; raises an exception on failure.
1515 """
1516 # In my testing, `force-stop` exits with status code 0 (success) so long
1517 # as you pass a package name, even if the package does not exist, or the
1518 # package is not running.
1519 try:
1520 self.run("shell", "am", "force-stop", package)
1521 except subprocess.CalledProcessError as e:
1522 raise BriefcaseCommandError(
1523 f"Unable to force stop app {package} on {self.device}"
1524 ) from e
1525
1526 def revoke_permission(self, package: str, permission: str) -> None:
1527 """Revoke a runtime permission for an app, specified as a package name.
1528
1529 :param package: The name of the Android package, e.g., com.username.myapp.
1530 :param permission: The name of the Android permission to revoke,
1531 e.g., android.permission.BLUETOOTH_SCAN.
1532 :returns: `None` on success; raises an exception on failure.
1533 """
1534 try:
1535 self.run("shell", "pm", "revoke", package, permission)
1536 except subprocess.CalledProcessError as e:
1537 raise BriefcaseCommandError(
1538 f"Unable to revoke permission {permission}"
1539 f"for app {package} on {self.device}"
1540 ) from e
1541
1542 def start_app(
1543 self, package: str, activity: str, passthrough: list[str], env: dict[str, str]
1544 ):
1545 """Start an app, specified as a package name & activity name.
1546
1547 If you have an APK file, and you are not sure of the package or activity
1548 name, you can find it using `aapt dump badging filename.apk` and looking
1549 for "package" and "launchable-activity" in the output.
1550
1551 :param package: The name of the Android package, e.g., com.username.myapp.
1552 :param activity: The activity of the APK to start.
1553 :param passthrough: Arguments to pass to the app.
1554 :param env: Environment variables to pass to the app.
1555 :returns: `None` on success; raises an exception on failure.
1556 """
1557 try:
1558 # `am start` also accepts string array extras, but we pass the arguments as
1559 # a single JSON string, because JSON deals with edge cases like whitespace
1560 # and escaping in a reliable and well-documented way.
1561 output = self.run(
1562 "shell",
1563 "am",
1564 "start",
1565 "-n",
1566 f"{package}/{activity}",
1567 "-a",
1568 "android.intent.action.MAIN",
1569 "-c",
1570 "android.intent.category.LAUNCHER",
1571 "--es",
1572 "org.beeware.ARGV",
1573 shlex.quote(json.dumps(passthrough)), # Protect from Android's shell
1574 *(
1575 [
1576 "--es",
1577 "org.beeware.ENVIRON",
1578 shlex.quote(json.dumps(env)), # Protect from Android's shell
1579 ]
1580 if env
1581 else []
1582 ),
1583 )
1584
1585 # `adb shell am start` always exits with status zero. We look for error
1586 # messages in the output.
1587 if any(
1588 line.startswith("Error: Activity class ")
1589 and line.endswith("does not exist.")
1590 for line in output.split("\n")
1591 ):
1592 raise BriefcaseCommandError(
1593 f"""\
1594 Activity class not found while starting app.
1595
1596 `adb` output:
1597
1598 {output}
1599 """
1600 )
1601 except subprocess.CalledProcessError as e:
1602 raise BriefcaseCommandError(
1603 f"Unable to start {package}/{activity} on {self.device}"
1604 ) from e
1605
1606 def logcat(self, pid: str) -> subprocess.Popen:
1607 """Start following the adb log for the device.
1608
1609 :param pid: The PID whose logs you want to display.
1610 :returns: A Popen object for the logcat call
1611 """
1612 # As best as we can make out, adb logcat returns UTF-8 output.
1613 # See #1425 for details.
1614 return self.tools.subprocess.Popen(
1615 [
1616 self.tools.android_sdk.adb_path,
1617 "-s",
1618 self.device,
1619 "logcat",
1620 "--format=tag",
1621 "--pid", # This option is available since API level 24.
1622 pid,
1623 ]
1624 # Filter out some noisy and useless tags.
1625 + [f"{tag}:S" for tag in ["EGL_emulation"]]
1626 + (["--format=color"] if self.tools.console.is_color_enabled else []),
1627 env=self.tools.android_sdk.env,
1628 encoding="UTF-8",
1629 stdout=subprocess.PIPE,
1630 stderr=subprocess.STDOUT,
1631 bufsize=1,
1632 )
1633
1634 def logcat_tail(self, since: datetime):
1635 """Show the tail of the logs for Python-like apps, starting from a given
1636 timestamp.
1637
1638 :param since: The start time from which logs should be displayed
1639 """
1640 try:
1641 # As best as we can make out, adb logcat returns UTF-8 output.
1642 # See #1425 for details.
1643 self.tools.subprocess.run(
1644 [
1645 self.tools.android_sdk.adb_path,
1646 "-s",
1647 self.device,
1648 "logcat",
1649 "--format=tag",
1650 "-t",
1651 since.strftime("%m-%d %H:%M:%S.000000"),
1652 "-s",
1653 # This is a collection of log labels that should catch
1654 # most Python app output.
1655 "MainActivity:*",
1656 "stdio:*",
1657 "python.stdout:*",
1658 "AndroidRuntime:*",
1659 ]
1660 + (["--format=color"] if self.tools.console.is_color_enabled else []),
1661 env=self.tools.android_sdk.env,
1662 check=True,
1663 encoding="UTF-8",
1664 )
1665 except subprocess.CalledProcessError as e:
1666 raise BriefcaseCommandError("Error starting ADB logcat.") from e
1667
1668 def forward(self, host_port: int, device_port: int):
1669 """Use the forward command to set up arbitrary port forwarding, which forwards
1670 requests on a specific host port to a different port on a device.
1671
1672 :param host_port: The port on the host that should be forwarded to the device
1673 :param device_port: The port on the device
1674 """
1675 try:
1676 self.tools.subprocess.check_output(
1677 [
1678 self.tools.android_sdk.adb_path,
1679 "-s",
1680 self.device,
1681 "forward",
1682 f"tcp:{host_port}",
1683 f"tcp:{device_port}",
1684 ],
1685 )
1686 except subprocess.CalledProcessError as e:
1687 raise BriefcaseCommandError("Error starting 'adb forward'.") from e
1688
1689 def forward_remove(self, host_port: int):
1690 """Remove forwarded port.
1691
1692 :param host_port: The port on the host that should be removed
1693 """
1694 try:
1695 self.tools.subprocess.check_output(
1696 [
1697 self.tools.android_sdk.adb_path,
1698 "-s",
1699 self.device,
1700 "forward",
1701 "--remove",
1702 f"tcp:{host_port}",
1703 ],
1704 )
1705 except subprocess.CalledProcessError as e:
1706 raise BriefcaseCommandError("Error starting 'adb forward --remove'.") from e
1707
1708 def reverse(self, device_port: int, host_port: int):
1709 """Use the reverse command to set up arbitrary port forwarding, which forwards
1710 requests on a specific device port to a different port on the host.
1711
1712 :param device_port: The port on the device that should be forwarded to the host
1713 :param host_port: The port on the host
1714 """
1715 try:
1716 self.tools.subprocess.check_output(
1717 [
1718 self.tools.android_sdk.adb_path,
1719 "-s",
1720 self.device,
1721 "reverse",
1722 f"tcp:{device_port}",
1723 f"tcp:{host_port}",
1724 ],
1725 )
1726 except subprocess.CalledProcessError as e:
1727 raise BriefcaseCommandError("Error starting 'adb reverse'.") from e
1728
1729 def reverse_remove(self, device_port: int):
1730 """Remove reversed port.
1731
1732 :param device_port: The port on the device that should be removed
1733 """
1734 try:
1735 self.tools.subprocess.check_output(
1736 [
1737 self.tools.android_sdk.adb_path,
1738 "-s",
1739 self.device,
1740 "reverse",
1741 "--remove",
1742 f"tcp:{device_port}",
1743 ],
1744 )
1745 except subprocess.CalledProcessError as e:
1746 raise BriefcaseCommandError("Error starting 'adb reverse --remove'.") from e
1747
1748 def pidof(self, package: str, **kwargs) -> str | None:
1749 """Obtain the PID of a running app by package name.
1750
1751 :param package: The package ID for the application (e.g.,
1752 ``org.beeware.tutorial``)
1753 :returns: The PID of the given app as a string, or None if it isn't
1754 running.
1755 """
1756 # The pidof command is available since API level 24. The level 23 emulator image
1757 # also includes it, but it doesn't work correctly (it returns all processes).
1758 try:
1759 # Exit status is unreliable: some devices (e.g. Nexus 4) return 0
1760 # even when no process was found.
1761 return self.run("shell", "pidof", "-s", package, **kwargs).strip() or None
1762 except subprocess.CalledProcessError:
1763 return None
1764
1765 def pid_exists(self, pid: str, **kwargs) -> bool:
1766 """Confirm if the PID exists on the emulator.
1767
1768 :param pid: The PID to check
1769 :returns: True if the PID exists, False if it doesn't.
1770 """
1771 # Look for the existence of /proc/<PID> on the device filesystem.
1772 # If that file exists, so does the process.
1773 try:
1774 self.run("shell", "test", "-e", f"/proc/{pid}", **kwargs)
1775 return True
1776 except subprocess.CalledProcessError:
1777 return False
1778
1779 def kill(self):
1780 """Stop the running Android emulator."""
1781 try:
1782 self.run("emu", "kill")
1783 except subprocess.CalledProcessError as e:
1784 raise BriefcaseCommandError("Error stopping the Android emulator.") from e
1785
1786 def datetime(self) -> datetime:
1787 """Obtain the device's current date/time.
1788
1789 This date/time is naive (i.e. not timezone aware) and in the device's "local"
1790 time. Therefore, it may be quite different from the date/time for Briefcase and
1791 caution should be used if comparing it to machine's "local" time.
1792 """
1793 datetime_format = "%Y-%m-%d %H:%M:%S"
1794 try:
1795 device_datetime = self.run("shell", "date", f"+'{datetime_format}'").strip()
1796 return datetime.strptime(device_datetime, datetime_format)
1797 except (ValueError, subprocess.CalledProcessError) as e:
1798 raise BriefcaseCommandError("Error obtaining device date/time.") from e