PC端如何通过USB线与Android设备通信

原理

通过 Socket 连接通信,将 PC 端作为客户端,Android 设备作为服务端
127.0.0.1 为设备本地地址

Android 与 PC 端通过端口通信,需要用到 forward 指令

adb forward tcp:8000 tcp:9000
将 PC 的8000端口的数据发送到 Android 设备9000端口
执行该指令之后才能通信

注意,该指令只能由 PC 端执行,故 Socket 方式不支持两台 Android 设备间通过 USB 通信

PC 端代码

public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1", 8000);
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            dos.writeUTF("send from pc");
            socket.close();
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

Android 端代码

class AndroidServer extends Thread {

        private boolean stop = false;

        public void setStop(boolean stop) {
            this.stop = stop;
        }

        @Override
        public void run() {
            ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(9000);
                while (!stop) {
                    Socket socket = serverSocket.accept();
                    DataInputStream inputStream = new DataInputStream(socket.getInputStream());
                    DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
                    final String msg = inputStream.readUTF();
                    Log.d(TAG, "msg: " + msg);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                    socket.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (serverSocket != null) {
                    try {
                        serverSocket.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    原文作者:海阔天空domybest
    原文地址: https://www.jianshu.com/p/49881d6a0fbb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞