模拟按鍵/輸入
在
adb shell
裡有個很實用的指令叫
input
,通過它可以做一些有趣的事情。
input
指令的完整 help 資訊如下:
Usage: input [<source>] <command> [<arg>...]
The sources are:
mouse
keyboard
joystick
touchnavigation
touchpad
trackball
stylus
dpad
gesture
touchscreen
gamepad
The commands and default sources are:
text <string> (Default: touchscreen)
keyevent [--longpress] <key code number or name> ... (Default: keyboard)
tap <x> <y> (Default: touchscreen)
swipe <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen)
press (Default: trackball)
roll <dx> <dy> (Default: trackball)
比如使用
adb shell input keyevent <keycode>
指令,不同的 keycode 能實作不同的功能,完整的 keycode 清單詳見 KeyEvent,摘引部分我覺得有意思的如下:
keycode | 含義 |
3 | HOME 鍵 |
4 | 傳回鍵 |
5 | 打開撥号應用 |
6 | 挂斷電話 |
24 | 增加音量 |
25 | 降低音量 |
26 | 電源鍵 |
27 | 拍照(需要在相機應用裡) |
64 | 打開浏覽器 |
82 | 菜單鍵 |
85 | 播放/暫停 |
86 | 停止播放 |
87 | 播放下一首 |
88 | 播放上一首 |
122 | 移動光标到行首或清單頂部 |
123 | 移動光标到行末或清單底部 |
126 | 恢複播放 |
127 | 暫停播放 |
164 | 靜音 |
176 | 打開系統設定 |
187 | 切換應用 |
207 | 打開聯系人 |
208 | 打開月曆 |
209 | 打開音樂 |
210 | 打開電腦 |
220 | 降低螢幕亮度 |
221 | 提高螢幕亮度 |
223 | 系統休眠 |
224 | 點亮螢幕 |
231 | 打開語音助手 |
276 | 如果沒有 wakelock 則讓系統休眠 |
下面是
input
指令的一些用法舉例。
電源鍵
指令:
adb shell input keyevent 26
執行效果相當于按電源鍵。
菜單鍵
指令:
adb shell input keyevent 82
HOME 鍵
指令:
adb shell input keyevent 3
傳回鍵
指令:
adb shell input keyevent 4
音量控制
增加音量:
adb shell input keyevent 24
降低音量:
adb shell input keyevent 25
靜音:
adb shell input keyevent 164
媒體控制
播放/暫停:
adb shell input keyevent 85
停止播放:
adb shell input keyevent 86
播放下一首:
adb shell input keyevent 87
播放上一首:
adb shell input keyevent 88
恢複播放:
adb shell input keyevent 126
暫停播放:
adb shell input keyevent 127
點亮/熄滅螢幕
可以通過上文講述過的模拟電源鍵來切換點亮和熄滅螢幕,但如果明确地想要點亮或者熄滅螢幕,那可以使用如下方法。
點亮螢幕:
adb shell input keyevent 224
熄滅螢幕:
adb shell input keyevent 223
滑動解鎖
如果鎖屏沒有密碼,是通過滑動手勢解鎖,那麼可以通過
input swipe
來解鎖。
指令(參數以機型 Nexus 5,向上滑動手勢解鎖舉例):
adb shell input swipe 300 1000 300 500
參數
300 1000 300 500
分别表示
起始點x坐标 起始點y坐标 結束點x坐标 結束點y坐标
。
輸入文本
adb shell input text hello