Get the currently focused app name. Args: device_id: Optional HDC device ID for multi-device setups. Returns: The app name if recognized, otherwise "System Home".
(device_id: str | None = None)
| 11 | import re |
| 12 | |
| 13 | def get_current_app(device_id: str | None = None) -> str: |
| 14 | """ |
| 15 | Get the currently focused app name. |
| 16 | |
| 17 | Args: |
| 18 | device_id: Optional HDC device ID for multi-device setups. |
| 19 | |
| 20 | Returns: |
| 21 | The app name if recognized, otherwise "System Home". |
| 22 | """ |
| 23 | hdc_prefix = _get_hdc_prefix(device_id) |
| 24 | |
| 25 | # Use 'aa dump -l' to list running abilities |
| 26 | result = _run_hdc_command( |
| 27 | hdc_prefix + ["shell", "aa", "dump", "-l"], |
| 28 | capture_output=True, |
| 29 | text=True, |
| 30 | encoding="utf-8" |
| 31 | ) |
| 32 | output = result.stdout |
| 33 | # print(output) |
| 34 | if not output: |
| 35 | raise ValueError("No output from aa dump") |
| 36 | |
| 37 | # Parse missions and find the one with FOREGROUND state |
| 38 | # Output format: |
| 39 | # Mission ID #139 |
| 40 | # mission name #[#com.kuaishou.hmapp:kwai:EntryAbility] |
| 41 | # app name [com.kuaishou.hmapp] |
| 42 | # bundle name [com.kuaishou.hmapp] |
| 43 | # ability type [PAGE] |
| 44 | # state #FOREGROUND |
| 45 | # app state #FOREGROUND |
| 46 | |
| 47 | lines = output.split("\n") |
| 48 | foreground_bundle = None |
| 49 | current_bundle = None |
| 50 | |
| 51 | for line in lines: |
| 52 | # Track the current mission's bundle name |
| 53 | if "app name [" in line: |
| 54 | match = re.search(r'\[([^\]]+)\]', line) |
| 55 | if match: |
| 56 | current_bundle = match.group(1) |
| 57 | |
| 58 | # Check if this mission is in FOREGROUND state |
| 59 | if "state #FOREGROUND" in line or "state #foreground" in line.lower(): |
| 60 | if current_bundle: |
| 61 | foreground_bundle = current_bundle |
| 62 | break # Found the foreground app, no need to continue |
| 63 | |
| 64 | # Reset current_bundle when starting a new mission |
| 65 | if "Mission ID" in line: |
| 66 | current_bundle = None |
| 67 | |
| 68 | # Match against known apps |
| 69 | if foreground_bundle: |
| 70 | for app_name, package in APP_PACKAGES.items(): |
no test coverage detected