***需求分析:***有时候使用ADB shell input keyevent 26 命令打开屏幕时,若屏幕本身状态已处于亮屏时,执行此命令则会关闭屏幕。为此,需要在激活屏幕前,加入屏幕当前状态判断函数用于判断屏幕当前状态。需要说明的是,keevent 26 对应事件为 电源键。
***实现路径分析:***本文是通过ADB shell dumpsys display 命令,获取屏幕当前信息,并筛取“mState = ” 的值,用于判断屏幕当前状态。若值为“ON”,则表示屏幕处于亮屏状态;若为“OFF”,则表示屏幕处于息屏状态。
具体代码如下:
def is_ScreenOn(): #判断屏幕是否点亮
print("正在执行is_ScreenOn()")
adb_command = ['E:/platform-tools/adb', 'shell', 'dumpsys', 'display'] # 构建adb命令,使用绝对路径引用ADB,此处需替换您设备上的ADB绝对路径
# 使用subprocess.run执行命令并捕获输出文本
# 注意:这里使用了text=True来确保输出是字符串而不是字节序列(在Python 3.7+中可用)
# 在旧版本的Python中,您可能需要使用universal_newlines=True并处理bytes输出
try:
result = subprocess.run(adb_command, capture_output=True, text=True, check=True)
display_content = result.stdout # 将dispaly展示内容捕获,并存为字符串
for line in display_content.split("\n"): # 遍历字符串的每一行
if "mState=ON" in line: #mstate=On,表示屏幕已点亮,=OFF表示屏幕未点亮
print("屏幕已点亮")
return True
break
else:
print("请点亮屏幕")
return False
except Exception as e:
print("发生了错误:"+e)
else:
print("is_ScreenOn程序执行完毕")