Android 使用USB与PC通信之ADB方式

Android 使用USB与PC通信之ADB方式

之前介绍过一篇使用UsbAccessary模式来与pc通信的文章点击链接

本篇文章介绍使用adb来进行与pc端的usb通信

首先必须确保手机要打开开发者模式

android端建立socket服务端,监听10010端口

        try {
            // 实例化ServerSocket对象并设置端口号为 10010
            mServerSocket = new ServerSocket();
            mServerSocket.setReuseAddress(true);
            mServerSocket.bind(new InetSocketAddress(10010));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        while (!stopFlag) {
            if (mServerSocket != null) {
                try {
                    // 等待客户端的连接(阻塞)
                    clientSocket = mServerSocket.accept();
                    inputStream = clientSocket.getInputStream();
                    outputStream = clientSocket.getOutputStream();

                    if (clientSocket != null) {
                        mReceiveThread = new ReceiveThread(inputStream);
                        // 开启接收线程
                        mReceiveThread.start();
                        EventBus.getDefault().post(new MessageEvent(SocketUtils.CON, SocketUtils.HOST));
                    }

                } catch (IOException e) {
                    // TODO Auto-generated catch block

                    e.printStackTrace();
                }

            }
        }

pc端程序需要执行一条命令adb forward命令,将10010端口(android端socket端口)数据转发到10086端口上,执行命令后最好阻塞一段时间

        try {
            Runtime.getRuntime()
                    .exec("adb forward tcp:10086 tcp:10010");
            Thread.sleep(1000);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

pc端建立socket客户端,连接10086端口

        Socket socket = null;
        try {
            InetAddress serverAddr = null;

            serverAddr = InetAddress.getByName("127.0.0.1");
            System.out.println("TCP 1" + "C: Connecting...");
            socket = new Socket(serverAddr, 10086); // 10010 是 PC 的端口,已重定向到;
            // Device 的 10086 端口

            SendADBThread sendADBThread = new SendADBThread(socket);
            sendADBThread.start();

            ReceADBThread receADBThread = new ReceADBThread(socket);
            receADBThread.start();

        } catch (UnknownHostException e1) {
            System.out.println("TCP 2" + "ERROR: " + e1.toString());
        } catch (IOException e2) {
            System.out.println("TCP 3" + "ERROR: " + e2.toString());
        }

socket连上后就可以进行通讯了,

其他细节可以参考demo

demo使用方式: 首先在手机上打开app,然后在运行pc端程序

demo下载: https://github.com/GavinAndre/UsbAccessoryDemo

你可能感兴趣的:(Android)