使用USB数据线连接PC端和Android端进行数据的交互

背景

公司有这样一个需求,一个萤火虫的开发板子,不要图形化界面,并且将公司的算法集成到板子中,由PC端传递数据到板子中进行数据的操作将结果返回给PC端,要使用USB来进行连接。这里的使用USB连接不是指,将手机当成一个U盘一样的东西存个文件就可以了。查阅了一些资料,总结一下遇到的问题,以及实现的步骤。

简单了解

  1. 虽然是使用USB连接,但是应用的技术还是Socket进行数据的传递工作。
  2. PC端的IP地址都是不同的,而手机或者Pad的的IP默认是“127.0.0.1”,所以手机端就不能是client端了,而是要使用PC端作为client端主动发起请求连接。
  3. 需要将adb命令配置到path中,否则会报错,因为adb命令不是系统级别的命令,是不能执行的,一般我们SDK中都是有adb.exe文件的,在sdk/platform-tools下。

PC端

1: 先执行adb命令,这些命令在cmd中也可以执行
//避免重复开启service所以在转发端口前先stop一下 
Runtime.getRuntime().exec("adb shell am broadcast -a NotifyServiceStop");
//转发的关键代码 只执行这两句命令也可以实现转发
Runtime.getRuntime().exec("adb forward tcp:10086 tcp:10010");//端口号根据自己的需求
Runtime.getRuntime().exec("adb shell am broadcast -a NotifyServiceStart");
 2:接下来就是Socket通讯了
public static void createSocket() {
        try {
            final Socket client = new Socket("127.0.0.1", 10086);

            // 得到socket管道中的输出流--------------像手机端写数据
            final BufferedOutputStream out = new BufferedOutputStream(client.getOutputStream());
            // 得到socket管道中的输人流--------------读取手机端的数据
            final BufferedInputStream in = new BufferedInputStream(client.getInputStream());
            new Thread(new Runnable() {

                @Override
                public void run() {
                    String readMsg = "";
                    while(true) {
                        if(!client.isConnected()) {
                            break;
                        }
                        readMsg = readMsgFromSocket(in);
                        if(readMsg.length() == 0) {
                            break;
                        }
                        // 将要返回的数据发送给pc 
                        try {
                            out.write((readMsg + "1").getBytes());
                            out.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
    //一个读取输入流的方法
    public static String readMsgFromSocket(InputStream in) {
        String msg = "";
        byte[] tempbuffer = new byte[1024];
        try {
            int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);
            msg = new String(tempbuffer, 0, numReadedBytes, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return msg;
    }

Android端

Android端作为服务端我们只需要监听端口即可
class SocketServerThread extends Thread {

        private BufferedOutputStream out;
        private Socket client;

        @Override
        public void run() {
            try {
                Log.e("wsy", "等待连接");
                System.out.println("---------socket 通信线程----等待连接");
                ServerSocket serverSocket = new ServerSocket(10010);
                while (true) {
                    client = serverSocket.accept();
                    out = new BufferedOutputStream(client.getOutputStream());
                    // 开启子线程去读去数据
                    new Thread(new SocketReadThread(new BufferedInputStream(client.getInputStream()))).start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //暴露给外部调用写入流的方法
        public void SendMsg(String msg) {
            String msg_1 = msg;
            try {
                out.write(msg_1.getBytes("UTF-8"));
                out.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        class SocketReadThread implements Runnable {

            private BufferedInputStream in;

            public SocketReadThread(BufferedInputStream inStream) throws IOException {
                this.in = inStream;
            }

            public void run() {
                try {
                    String readMsg = "";
                    while (true) {
                        try {
                            if (!client.isConnected()) {
                                break;
                            }
                            //   读到后台发送的消息  然后去处理
                            String readMsg= readMsgFromSocket(in);
                            //    处理读到的消息(主要是身份证信息),然后保存在sp中;
                            if (readMsg.length() == 0) {
                                break;
                            }
                            //  将要返回的数据发送给 pc
                            out.write((readMsg + "flag").getBytes());
                            out.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    in.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            //读取PC端发送过来的数据
            private String readMsgFromSocket(InputStream in) {
                String msg = "";
                byte[] temp = new byte[1024];
                try {
                    int readedBytes = in.read(temp, 0, temp.length);
                    msg = new String(temp, 0, readedBytes, "utf-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return msg;
            }
        }
    }

OK,以上就是使用USB连接Android和PC进行数据交互的简单实现了。
源码下载地址:https://download.csdn.net/download/qq_38001118/10476677
如果有什么扩展的需求或者我有什么遗失和错误欢迎评论,我会第一时间回复和更新。

猜你喜欢

转载自blog.csdn.net/qq_38001118/article/details/80679616