修复hdc的get_current_app函数

This commit is contained in:
floatingstarZ
2025-12-22 10:29:57 +08:00
parent 1ab6e1edf6
commit 75f0e26ae4

View File

@@ -8,7 +8,7 @@ from typing import List, Optional, Tuple
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:
"""
@@ -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")
raise ValueError("No output from aa dump")
# 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
# 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"
@@ -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())