如何使用 USB 调试向 android 设备发送快速实时输入命令?

How to send fast live input commands to android device using USB debugging?

我想在我的电脑上配置一些按键,以便在按下它们时触发我的 android 设备上的特定触摸输入操作。

例如:- 按 K 表示触摸输入屏幕中心等。使用鼠标控制屏幕。

但是,有两个问题我无法解决:-

(1) adb shell 速度太慢,无法使用。由于使用 java.

的工作方式,它有超过一秒的延迟

我需要它尽可能快。

(2) 我找不到发送实时触摸输入的方法,大多数工具只是记录手势并执行它们。

如果您正在测试您的应用程序或只是通过代码使用它,您可以使用 Android Testing tools like Espresso or preferably AndroidX testing 套件(捆绑在 Google 的 Jetpack 中)编写与您的应用程序的大多数用户交互。 =12=]

使用像 Espresso 这样的 UI 测试工具的优势在于它能够等待用户触摸和设备或模拟器响应之间的不确定持续时间。

这些测试 运行 在设备上最快。当您 运行 测试时,您会看到屏幕快速交互。

如果您 运行 在模拟器上进行这些测试,由于模拟器固有的缓慢特性及其对系统硬件的依赖性,它会很慢。如果您使用 Firebase Test Lab.

在设备上或云端 运行 最好

您可以通过以下步骤实现此目的

开发一个作为服务器运行并在设备内部的端口上侦听命令的应用程序

可以从 adb shell instrumentation command/service 调用该应用程序。下面的一些代码可以从您的 PC 接收命令(字符串)并执行您需要的操作。

public void startServer() throws Exception {

    try {
        serverSocket = new ServerSocket(8080);
        CLIENT_SOCKET = serverSocket.accept();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                CLIENT_SOCKET.getInputStream()));

        String inputLine;
        // Starting server
        while ((inputLine = in.readLine()) != null) {
            //out(inputLine);
            // do whatever with inputLine, handle touches for 'K'
        }
    } catch (IOException e) {
           //err in connection, handle
    }

将您的本地端口转发到 adb 内的端口 shell(即应用程序侦听的设备端口)

adb forward tcp:8080 tcp:8080

以上命令将本地 PC 端口 8080 转发到您的 adb 中的 8080 端口 shell device/emulator.

连接的客户端(您的 PC)端程序或脚本,将命令发送到本地端口,然后到达 shell

python

中的示例代码
 import socket
 soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 soc.connect(('127.0.0.1', 8080))
 soc.send('k\n') # this will reach inside the startServer function of app.

以上只是一些示例代码,网上会有很多其他complete上述步骤的示例。