python脚本通过adb控制手机操作

1,999 阅读3分钟

一些adb命令

查看应用列表

adb shell pm list packages [-?] [--user USER_ID] [FILTER]

参数 显示列表
所有应用
-f 显示应用关联的apk文件
-d 只显示disabled的应用
-e 只显示 enable的应用
-s 只显示系统应用
-3 只显示第三方应用
-i 只显示应用的installer
-u 包含已卸载应用
T:string 包名包含T的应用

安装应用

adb install [?] [apk-file]

参数 含义
-l 将应用安装到保护目录/mnt/esec
-r 允许覆盖安装
-t 允许安装AndroidManifest里application指定android:testonly=“true”的应用
-s 将应用安装到sdcard
-d 允许降级安装
-g 授予所有运行时权限

运行后会有返回信息

卸载应用

adb uninstall [-k] [package-name]

-k可选,表示卸载应用但保留数据和缓存目录

查看前台activity

adb shell dumpsys activity activities

查看应用详细信息

adb shell dumpsys package [package-name]

与应用交互

与应用交互主要是使用 am 命令,常用的命令如下:

command 用途
start [options] <intent> 启动<intent>指定的activity
Startservice [options] <intent> 启动<intent>指定的service
broadcast [options] <intent> 发送<intent>指定的广播
force-stop [package-name] 停止相关进程

用于决定 intent 对象的选项如下:

参数 含义
-a 指定 action,比如 android.intent.action.VIEW
-c 指定 category,比如 android.intent.category.APP_CONTACTS
-n 指定完整 component 名,用于明确指定启动哪个 Activity

<intent> 里还能带数据,就像写代码时的 Bundle 一样:

参数 含义
--esn<extra-key> null 值(只有 key 名)
-e|--es<extra-key> <extra-string-value> string 值
--ez<extra-key> <extra-boolean-value> boolean 值
--ei<extra-key> <extra-int-value> integer 值
--el<extra-key> <extra-long-value> long 值
--ef<extra-key> <extra-float-value> float 值
--eu<extra-key> <extra-uri-value> URI
--ecn<extra-key> <extra-component-name-value> component name
--eia <extra-key><extra-int-value>[,<extra-int-value...>] integer 数组
--ela <extra-key> <extra-long-value>[,<extra-long-value...>] long 数组

模拟点击

Usage: input [<source>] <command> [<arg...>]

The sources are: dpad keyboard mouse touchpad gamepad touchnavigation joystick touchscreen stylus trackball

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) draganddrop <x1> <y1> <x2> <y2> [duration(ms)] (Default: touchscreen) press (Default: trackball) roll <dx> <dy> (Default: trackball)

使用 adb shell input keyevent 命令,不同的 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 则让系统休眠

获取ui树

adb shell uiautomator dump --compressed filepath(手机上保存的目录)

将ui树拉取到电脑

adb pull /data/local/tmp/uidump.xml filepath(电脑上保存的目录)

在python上调用adb

import os

os.popen("adb shell uiautomator dump --compressed 'filepath'") 即可调用,还可以.read获取返回值

通过对从手机拉取的ui树进行解析,可以获取当前页面的所有控件位置,可以自动的进行一些例如点击滑动等重复性的工作.