Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 49 additions & 11 deletions phone_agent/hdc/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from phone_agent.config.apps_harmonyos import APP_ABILITIES, APP_PACKAGES
from phone_agent.config.timing import TIMING_CONFIG
from phone_agent.hdc.connection import _run_hdc_command

import re

def get_current_app(device_id: str | None = None) -> str:
"""
Expand All @@ -22,23 +22,58 @@ def get_current_app(device_id: str | None = None) -> str:
"""
hdc_prefix = _get_hdc_prefix(device_id)

# Use 'aa dump -l' to list running abilities
result = _run_hdc_command(
hdc_prefix + ["shell", "hidumper", "-s", "WindowManagerService", "-a", "-a"],
hdc_prefix + ["shell", "aa", "dump", "-l"],
capture_output=True,
text=True,
encoding="utf-8"
)
output = result.stdout
# print(output)
if not output:
raise ValueError("No output from hidumper")

# Parse window focus info
for line in output.split("\n"):
if "focused" in line.lower() or "current" in line.lower():
for app_name, package in APP_PACKAGES.items():
if package in line:
return app_name

raise ValueError("No output from aa dump")

# Parse missions and find the one with FOREGROUND state
# Output format:
# Mission ID #139
# mission name #[#com.kuaishou.hmapp:kwai:EntryAbility]
# app name [com.kuaishou.hmapp]
# bundle name [com.kuaishou.hmapp]
# ability type [PAGE]
# state #FOREGROUND
# app state #FOREGROUND

lines = output.split("\n")
foreground_bundle = None
current_bundle = None

for line in lines:
# Track the current mission's bundle name
if "app name [" in line:
match = re.search(r'\[([^\]]+)\]', line)
if match:
current_bundle = match.group(1)

# Check if this mission is in FOREGROUND state
if "state #FOREGROUND" in line or "state #foreground" in line.lower():
if current_bundle:
foreground_bundle = current_bundle
break # Found the foreground app, no need to continue

# Reset current_bundle when starting a new mission
if "Mission ID" in line:
current_bundle = None

# Match against known apps
if foreground_bundle:
for app_name, package in APP_PACKAGES.items():
if package == foreground_bundle:
return app_name
# If bundle is found but not in our known apps, return the bundle name
print(f'Bundle is found but not in our known apps: {foreground_bundle}')
return foreground_bundle
print(f'No bundle is found')
return "System Home"


Expand Down Expand Up @@ -270,3 +305,6 @@ def _get_hdc_prefix(device_id: str | None) -> list:
if device_id:
return ["hdc", "-t", device_id]
return ["hdc"]

if __name__ == "__main__":
print(get_current_app())