ADB 技巧
获取当前 Activity 名称
获取当前 Activity 名称:
bash
adb shell dumpsys activity | grep "mResumedActivity"
获取包名列表
bash
adb shell pm list packages
获取屏幕截图
bash
adb exec-out screencap -p > screen.png
打开指定应用
bash
adb shell monkey -p com.example.app -c android.intent.category.LAUNCHER 1
输入 Unicode 文本
使用 ADB 输入中文需要安装 ADBKeyBoard,然后使用以下命令:
bash
adb shell ime enable com.android.adbkeyboard/.AdbIME
adb shell ime set com.android.adbkeyboard/.AdbIME
Python 示例:
python
import base64
import subprocess
def _run_cmd(
cmd: list[str],
timeout: float | None = None,
) -> tuple[int, bytes, bytes]:
"""运行命令"""
# logger.debug(f"$ {' '.join(cmd)}")
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = proc.communicate(timeout=timeout)
return (
proc.returncode,
stdout,
stderr,
)
class AdbServices:
def __init__(self, serial: str) -> None:
self._serial = serial
@classmethod
def _adb(cls, cmd: list[str], timeout: float | None = None, raise_exception=True):
code, stdout, stderr = _run_cmd(["adb"] + cmd, timeout)
stdout_str = stdout.decode("utf-8", "ignore")
if code != 0 and raise_exception:
stderr_str = stderr.decode("utf-8", "ignore")
# logger.error("Exception: " + stderr_str.strip())
raise Exception(stderr_str)
# if stdout_str:
# logger.debug(">>>\n" + stdout_str.strip())
return stdout_str
def call(
self,
cmd: list[str],
timeout: float | None = None,
raise_exception=True,
) -> str:
"""运行命令"""
return self._adb(["-s", self._serial] + cmd, timeout, raise_exception)
def input_unicode_text(self, text: str):
"""输入 Unicode 文本"""
b64 = str(base64.b64encode(text.encode("utf-8")))[1:]
return self.call(
[
"shell",
"am",
"broadcast",
"-a",
"ADB_INPUT_B64",
"--es",
"msg",
b64,
]
)