import re import subprocess class SimpleTester: def __init__(self): # 模拟 logger,防止运行报错 self.logger = type('MockLogger', (), {'warning': lambda self, msg: print(f"LOG WARNING: {msg}")})() def adb_shell(self, cmd): """执行真实的 ADB 命令""" try: # 这里的 shell=True 是为了支持管道符 | grep result = subprocess.check_output(f"adb shell \"{cmd}\"", shell=True, stderr=subprocess.STDOUT) return result.decode('utf-8') except Exception as e: return "" def get_current_package(self): """ 这是你提供的原函数逻辑 """ try: # 优先使用 mCurrentFocus focus_out = self.adb_shell("dumpsys window | grep mCurrentFocus") if 'mCurrentFocus' in focus_out: pkg_match = re.search(r'Window\{[a-f0-9]+\s+\S+\s+([^/]+)/', focus_out) if pkg_match: current_pkg = pkg_match.group(1) return current_pkg # 备选:从 mResumedActivity 中提取 resumed_out = self.adb_shell("dumpsys activity activities | grep mResumedActivity") if 'mResumedActivity' in resumed_out: pkg_match = re.search(r'\{[a-f0-9]+\s+\S+\s+([^/]+)/', resumed_out) if pkg_match: current_pkg = pkg_match.group(1) return current_pkg except Exception as e: self.logger.warning(f"Error getting current package: {e}") return None # --- 执行测试 --- if __name__ == "__main__": tester = SimpleTester() print("正在尝试获取当前手机前台包名...") result = tester.get_current_package() if result: print(f"成功!当前包名为: 【 {result} 】") else: print("失败:未能获取包名。请检查:") print("1. 手机是否已连接并开启 ADB 调试") print("2. 屏幕是否已解锁并处于某个 App 界面")