Android/adb

Android/adb

adb 是 SDK Platform Tools 里提供的PC端命令行下 Android 手机管理工具。使用前需要安装 usb adb 驱动(SDK Platform Tools 里自带,也可以用 Windows 10 自动查找驱动)。

需要在 Android 手机 设置 - 开发者选项 里打开 usb debug,并在第一次连接 PC 时在手机上弹出的对话框里选择“信任该PC”。这将信任该PC的RSA公钥。

PC上 adb 使用的公钥保存在用户文件夹里,第一次运行 adb 时自动生成。保存路径为 Linux: ~/.android/adbkey.pub 或 Windows: %USERPROFILE%\.android\adbkey.pub

Multiple devices

如果 adb 连接了多个设备,用 -s deviceId 参数指定设备 id。设备 id 用 adb devices 查看。注意 -s 参数必须出现在具体的 adb 命令之前:

adb -s 127.0.0.1:58526 shell

CLI

# 将 SD 卡指定文件或目录复制到PC某个目录下
# -a 参数保留文件的创建/修改时间戳。(但反向的 adb push 没有 -a 参数)
# Windows 下,adb pull / push 对于非 Ascii 字符文件名可能会导致文件名乱码。
adb pull -a /sdcard/DCIM .

# 将文件传输到 sd 卡。必须指定完整远程路径(而不能只指定复制到的目录路径)
adb push file.rar /sdcard/file.rar

# 安装 apk
# 如果 app 已经安装过,必须加 -r 参数才能(覆盖)安装(签名必须相同才可以覆盖)
adb install -r app-release.apk

shell

  • adb shell input keyevent 26 : 等效于按电源键(关闭/开启屏幕)。
  • adb shell settings put secure install_non_market_apps 1 : 允许安装未知来源app。输出1表示成功
  • adb shell /system/bin/pm install -t /data/local/tmp/app.apk : 安装Android设备上本地apk
  • adb shell am start com.example.app/.MainActivity : 启动 App 的 Activity
  • adb shell /system/bin/pm uninstall com.example.app : 根据包名卸载 app

logcat

adb logcat -c # clear all
adb logcat -s TagName # filter by tagname

模拟输入

adb 可以完全模拟手机输入。

adb shell "input keyevent 26" This will press the power button for waking up the screen.

adb shell "input swipe 300 1000 300 300" This will slide up the screen. Now your phone is clearly unlocked.

远程控制

Scrcpy

App 管理

禁用系统 system app

# list all apps
adb shell pm list packages

adb shell pm disable-user --user 0 <package_to_disable>

# list disabled apps
adb shell pm list packages -d

adb shell pm enable <package_to_disable>
adb shell cmd package list packages
adb shell "pm uninstall com.example.app"

Wireless adb

需要 Android 11+。

在手机 Developer Options 里开启 Wireless Debug (菜单右边的开关), 然后点击这个菜单项进入子菜单界面。选择 Pair With code,保持打开的对话框不要关闭。

然后在电脑上输入 "adb pair ip:port" 并输入手机上对话框里显示的6位数字 pair digits 完成配对。

然后用 adb connect ip:port 连接手机,port 是手机上 Wireless Debug 子菜单界面顶部显示的端口。

shizuku 这个工具可以利用 Wireless adb 激活小黑屋等需要 root 或连接电脑才能使用的工具。

说明

  • adb pair 需要较新版本的 platform tools (Download: Windows, Linux)。
  • Android 11+ 好像手机上 Wireless adb 的端口是随机的,而以前是固定 5555。导致每次都必须输入端口,很烦。

Last update: 2023-02-08 01:25:44 UTC