Window下adb shell 显示乱码解决方式

本文介绍了解决在Windows环境下使用ADB Shell时遇到的颜色代码干扰问题。通过设置命令别名,可以关闭颜色输出,使文件列表更加清晰易读。

window下打开adb shell

ls显示时,出现颜色前后缀,非常不方便查看,是因为adb中输出了颜色,但是window不支持,所以要把他关掉

用如下方式:
alias ls='busybox ls --color=never'

 

 

<think>我们正在解决Windows环境下执行命令`adbshelldumpsyswindowwindows|findstr"mCurrentFocusmFocusedApp"`时返回非零退出状态1的问题。这个错误通常意味着命令执行失败,可能的原因包括:1.没有找到匹配的字符串(即findstr没有找到包含"mCurrentFocus"或"mFocusedApp"的行)2.ADB连接问题(设备未连接或未授权)3.设备上没有窗口服务(dumpsyswindow命令无输出)解决方案:步骤1:检查设备连接运行`adbdevices`确保设备已连接并授权。步骤2:尝试单独运行`adbshelldumpsyswindowwindows`,观察输出中是否包含"mCurrentFocus"或"mFocusedApp"。如果输出中没有这些关键词,可能是设备系统差异,可以尝试其他关键词。步骤3:调整命令,尝试只使用一个关键词,因为有些设备可能只显示其中一个。例如:`adbshelldumpsyswindowwindows|findstr"mCurrentFocus"``adbshelldumpsyswindowwindows|findstr"mFocusedApp"`步骤4:如果上述步骤失败,可以尝试使用更通用的命令获取当前包名:`adbshelldumpsysactivityactivities|findstr"mResumedActivity"`或者`adbshelldumpsysactivityactivities|findstr"mFocusedActivity"`步骤5:如果仍然无法获取,可以尝试使用`adbshelldumpsysactivitytop`来获取顶层活动的包名。具体到我们的函数`get_current_package`,我们可以修改为尝试多种方法:修改后的函数:1.首先尝试使用`mCurrentFocus`和`mFocusedApp`2.如果失败,尝试使用`mResumedActivity`或`mFocusedActivity`3.再失败,尝试使用`dumpsysactivitytop`同时,我们需要注意,在Windows中,管道符和findstr的使用需要正确转义,但我们在subprocess中直接使用shell=True,所以应该没问题。我们重新设计一个更健壮的`get_current_package`函数:```pythondefget_current_package():try:#方法1:使用mCurrentFocus或mFocusedAppcmd1='adbshelldumpsyswindowwindows|findstr"mCurrentFocusmFocusedApp"'output1=subprocess.check_output(cmd1,shell=True).decode('gbk').strip()pattern=r'[a-zA-Z0-9._]+(?=/|$)'match=re.search(pattern,output1)ifmatch:returnmatch.group(0)#方法2:使用dumpsysactivityactivities查找mResumedActivity或mFocusedActivitycmd2='adbshelldumpsysactivityactivities|findstr"mResumedActivitymFocusedActivity"'output2=subprocess.check_output(cmd2,shell=True).decode('gbk').strip()#在输出中查找包名,例如:mResumedActivity:ActivityRecord{...com.example.app/.MainActivity}match=re.search(r'[a-zA-Z0-9._]+(?=/|$)',output2)ifmatch:returnmatch.group(0)#方法3:使用dumpsysactivitytopcmd3='adbshelldumpsysactivitytop|findstr"ACTIVITY"'output3=subprocess.check_output(cmd3,shell=True).decode('gbk').strip()#输出示例:ACTIVITYcom.example.app/.MainActivitypid=1234match=re.search(r'ACTIVITY\s+([a-zA-Z0-9._]+)/',output3)ifmatch:returnmatch.group(1)return"unknown"exceptsubprocess.CalledProcessErrorase:print(f"命令执行失败,返回码:{e.returncode}")return"unknown"exceptExceptionase:print(f"获取当前应用错误:{str(e)}")return"unknown"```注意:以上方法中,我们依次尝试三种不同的命令来获取当前包名。如果一种方法失败(没有输出或没有匹配),则尝试下一种。另外,由于ADB命令的输出可能因设备而异,建议在实际设备上测试这些命令。如果问题仍然存在,请检查设备是否处于亮屏状态(有些设备在锁屏时可能不会返回当前活动应用)。最后,我们可以在调用这个函数之前,先确保设备已经唤醒并解锁(可以通过adb命令模拟按键事件来实现,但需要设备有相应权限)。考虑到我们的性能监控脚本,如果设备锁屏,可能确实无法获取到当前应用,因此我们也可以考虑在脚本中加入唤醒屏幕的步骤(例如:`adbshellinputkeyeventKEYCODE_WAKEUP`)和解锁(例如发送滑动事件)。不过,这些操作可能会影响性能测试,所以需要根据实际情况决定。现在,我们修改`get_current_package`函数,使其更加健壮,并处理可能的错误。同时,我们也可以考虑在命令执行失败时,增加重试机制。由于时间关系,我们先实现上述多命令尝试的方法。请根据实际情况调整。</think>### Windows环境下ADB命令执行错误解决方案 针对`adb shell dumpsys window windows | findstr "mCurrentFocus mFocusedApp"`返回非零退出状态1的问题,以下是完整的解决方案: #### 问题原因分析 1. **设备未连接或未授权**:ADB未正确连接设备 2. **命令语法差异**:Windows命令提示符与Linux shell的语法差异 3. **输出编码问题**:GBK编码处理不当导致乱码 4. **设备状态异常**:设备未唤醒或处于锁屏状态 5. **ADB服务未启动**:后台adb server未运行 #### 完整解决方案 ```python import subprocess import re import time def check_adb_connection(): """检查ADB设备连接状态""" try: # 列出已连接设备 devices = subprocess.check_output("adb devices", shell=True, stderr=subprocess.STDOUT).decode('gbk') # 检查设备授权状态 if "unauthorized" in devices: print("设备未授权USB调试,请检查手机弹窗") return False # 检查设备连接状态 if "device" not in devices: print("未检测到已连接设备,请检查USB连接") return False return True except Exception as e: print(f"ADB连接检查失败: {str(e)}") return False def get_current_package(): """获取当前前台应用包名(兼容Windows)""" try: # 方法1:直接使用dumpsys命令 output = subprocess.check_output( "adb shell dumpsys window windows", shell=True, stderr=subprocess.STDOUT ).decode('gbk', errors='ignore').strip() # 提取包名模式1 pattern1 = r'mCurrentFocus=Window\{.*?\s([a-zA-Z0-9._]+)/' match1 = re.search(pattern1, output) if match1: return match1.group(1) # 提取包名模式2 pattern2 = r'mFocusedApp=AppWindowToken\{.*?\s([a-zA-Z0-9._]+)/' match2 = re.search(pattern2, output) if match2: return match2.group(1) # 方法2:使用activity命令(备用方案) output = subprocess.check_output( "adb shell dumpsys activity activities | findstr ResumedActivity", shell=True, stderr=subprocess.STDOUT ).decode('gbk', errors='ignore').strip() pattern3 = r'([a-zA-Z0-9._]+)/' match3 = re.search(pattern3, output) return match3.group(1) if match3 else "unknown" except subprocess.CalledProcessError as e: # 处理退出状态1错误 if e.returncode == 1: print("命令执行失败,尝试重启ADB服务...") subprocess.run("adb kill-server", shell=True) subprocess.run("adb start-server", shell=True) time.sleep(2) return get_current_package() # 递归重试 print(f"命令执行错误: {e.output.decode('gbk', errors='ignore')}") return "unknown" except Exception as e: print(f"获取当前应用异常: {str(e)}") return "unknown" def wake_device(): """唤醒设备并解锁屏幕""" try: # 唤醒设备 subprocess.run("adb shell input keyevent KEYCODE_WAKEUP", shell=True) time.sleep(0.5) # 滑动解锁(根据设备调整坐标) subprocess.run("adb shell input swipe 300 1000 300 500", shell=True) time.sleep(0.5) except: pass if __name__ == "__main__": # 步骤1:检查设备连接 if not check_adb_connection(): exit(1) # 步骤2:唤醒设备 wake_device() # 步骤3:获取当前包名 package = get_current_package() print(f"当前前台应用: {package}") ``` #### 关键解决步骤 1. **ADB连接检查**: - 使用`adb devices`验证设备连接状态 - 检测`unauthorized`状态提示用户授权USB调试 - 确保至少有一个设备处于`device`状态[^1] 2. **命令错误处理**: ```python try: # 主命令执行 except subprocess.CalledProcessError as e: if e.returncode == 1: # 重启ADB服务 subprocess.run("adb kill-server", shell=True) subprocess.run("adb start-server", shell=True) time.sleep(2) # 重试命令 ``` 3. **多模式包名提取**: - 模式1:`mCurrentFocus=Window\{.*?\s([a-zA-Z0-9._]+)/` - 模式2:`mFocusedApp=AppWindowToken\{.*?\s([a-zA-Z0-9._]+)/` - 备用模式:`dumpsys activity activities | findstr ResumedActivity` 4. **设备唤醒解锁**: ```python # 物理唤醒 adb shell input keyevent KEYCODE_WAKEUP # 滑动解锁(需根据设备调整坐标) adb shell input swipe 300 1000 300 500 ``` 5. **编码处理优化**: ```python .decode('gbk', errors='ignore') # 忽略无法解码的字符 ``` #### 验证方法 1. 单独运行连接检查函数: ```python print("设备连接状态:", check_adb_connection()) ``` 2. 测试包名获取: ```python print("当前应用包名:", get_current_package()) ``` 3. 手动执行等效命令: ```cmd adb devices adb shell dumpsys window windows ``` #### 注意事项 1. 首次使用需在设备上**允许USB调试** 2. 解锁坐标需根据设备屏幕分辨率调整 3. 华为等特殊设备可能需要开启**"仅充电"模式下允许ADB调试** 4. 如遇持续失败,尝试`adb kill-server` + `adb start-server`重启服务 > **替代方案**:使用`adb shell dumpsys activity top`获取顶层活动信息,通常包含包名[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值