88from phone_agent .config .apps_harmonyos import APP_ABILITIES , APP_PACKAGES
99from phone_agent .config .timing import TIMING_CONFIG
1010from phone_agent .hdc .connection import _run_hdc_command
11-
11+ import re
1212
1313def get_current_app (device_id : str | None = None ) -> str :
1414 """
@@ -22,23 +22,58 @@ def get_current_app(device_id: str | None = None) -> str:
2222 """
2323 hdc_prefix = _get_hdc_prefix (device_id )
2424
25+ # Use 'aa dump -l' to list running abilities
2526 result = _run_hdc_command (
26- hdc_prefix + ["shell" , "hidumper " , "-s " , "WindowManagerService" , "-a" , "-a " ],
27+ hdc_prefix + ["shell" , "aa " , "dump " , "-l " ],
2728 capture_output = True ,
2829 text = True ,
2930 encoding = "utf-8"
3031 )
3132 output = result .stdout
33+ # print(output)
3234 if not output :
33- raise ValueError ("No output from hidumper" )
34-
35- # Parse window focus info
36- for line in output .split ("\n " ):
37- if "focused" in line .lower () or "current" in line .lower ():
38- for app_name , package in APP_PACKAGES .items ():
39- if package in line :
40- return app_name
41-
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 ():
71+ if package == foreground_bundle :
72+ return app_name
73+ # If bundle is found but not in our known apps, return the bundle name
74+ print (f'Bundle is found but not in our known apps: { foreground_bundle } ' )
75+ return foreground_bundle
76+ print (f'No bundle is found' )
4277 return "System Home"
4378
4479
@@ -270,3 +305,6 @@ def _get_hdc_prefix(device_id: str | None) -> list:
270305 if device_id :
271306 return ["hdc" , "-t" , device_id ]
272307 return ["hdc" ]
308+
309+ if __name__ == "__main__" :
310+ print (get_current_app ())
0 commit comments