安卓:无需连接USB即可远程调试(需adb root)

783 阅读2分钟
问题:
  1. 客户端运行在定制机器上,USB接口不对外暴露,调试时需要拆卸机器,如果使用WIFI调试,也需要先拆机输入adb命令,且重启后会失效
  2. 设备崩溃时提取LOG需要拆机连接,如果用远程调试更方便
  3. 测试人员在使用Appium时,电脑无法识别设备,USB接口和驱动的不稳定
分析:

由于设备的root权限可以拿到,用USB连接后尝试命令:

adb root

adb shell

setprop service.adb.tcp.port 5556

stop adbd

start adbd

再尝试用5556端口进行WIFI连接,结果如下:

image-20220113170111313

连接成功,说明该命令在设备上可以生效

在APP的Application中加入该脚本的执行,每次APP启动时会执行以上命令:

​
    /**
     * 打开WIFI调试,默认端口5555,可以不输入端口
     * 使用 adb connect device_ip 连接设备
     */
    private void enableWifiDebug() {
        try {
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            os.writeBytes("setprop service.adb.tcp.port 5555\n");
            os.writeBytes("stop adbd\n");
            os.writeBytes("start adbd\n");
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

此时出现问题:Appium无法连接APP,且以上代码没有回收输出流

分析:

修改网络调试端口,需要stop adbd + start adbd生效,连接Appium时会自动重启APP,命令

stop adbd

将会执行,而Appium是依赖adb与APP进行通信,所以Appium会断开

代码改为开启是判断端口是否已经改为5555了,如果是,就不再执行stop adbd

/**
 * 打开WIFI调试,默认端口5555,可以不输入端口
 * 使用 adb connect device_ip 连接设备
 */
private void enableWifiDebug() {
    DataOutputStream os = null;
    BufferedReader reader = null;;
    try {
        Process process = Runtime.getRuntime().exec("su");
        os = new DataOutputStream(process.getOutputStream());
        reader = new BufferedReader(new InputStreamReader(new DataInputStream(process.getInputStream())));
        os.writeBytes("getprop service.adb.tcp.port\n");
        os.flush();
        String port = reader.readLine();
        if (port.equals("5555")) { //没有这个,会导致每一次重启都会stop adbd,从而导致Appium无法连接
            return;
        }
        os.writeBytes("setprop service.adb.tcp.port 5555\n");
        os.writeBytes("stop adbd\n");
        os.writeBytes("start adbd\n");
        os.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (os != null) {
                os.close();
            }
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
​
    }
}
结果:

无需拆卸机器和数据线即可远程连接设备进行调试