Android蓝牙开发教程(三)——蓝牙设备相互通讯

在上一篇中已经介绍如何连接我们搜索到的蓝牙设备,如果你还没阅读过,建议先看看上一篇文章Android蓝牙开发教程(二)——连接蓝牙设备

在上一篇文章中,无论是自动连接还是被动连接,连接成功后,都是将获取到的BluetoothSocket交由连接线程ConnectThread来处理。

 @Override
        public void run() {
            try {
                ... ...
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();

                byte[] buffer = new byte[BUFFER_SIZE];
                int bytes;
                while (true) {
                    //读取数据
                    bytes = inputStream.read(buffer);
                    if (bytes > 0) {
                        final byte[] data = new byte[bytes];
                        System.arraycopy(buffer, 0, data, 0, bytes);
                        text_msg.post(new Runnable() {
                            @Override
                            public void run() {
                                text_msg.setText(getResources().getString(R.string.get_msg)+new String(data));
                            }
                        });
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                text_state.post(new Runnable() {
                    @Override
                    public void run() {
                        text_state.setText(getResources().getString(R.string.connect_error));
                    }
                });
            }

当连接成功后,就可以从BluetoothSocket中获取读数据和写数据的流接口。然后循环监听InputStream是否有获取到数据,最后将数据设置到TextView中展示出来。

 /**
         * 发送数据
         *
         * @param msg
         */
        public void sendMsg(final String msg) {

            byte[] bytes = msg.getBytes();
            if (outputStream != null) {
                try {
                    //发送数据
                    outputStream.write(bytes);
                    text_msg.post(new Runnable() {
                        @Override
                        public void run() {
                            text_msg.setText(getResources().getString(R.string.send_msgs)+msg);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                    text_msg.post(new Runnable() {
                        @Override
                        public void run() {
                            text_msg.setText(getResources().getString(R.string.send_msg_error)+msg);
                        }
                    });
                }
            }
        }

 

在发送数据的方法中,主要是用OutputStream写入数据并将写入成功后将写入的数据展示出来。

在这里只是简单的展示一下蓝牙设备之间是如何获取数据和发送数据。对于断开连接,重新连接等多种状况的处理这里就不再介绍了。在具体项目情况中再灵活变通就行了。

至此,本教程就结束了。如果有什么疑问,欢迎和本人一起探讨。

——————————————————————————————

github

csdn

 
 
posted @ 2017-07-10 23:37  专注it  阅读(3692)  评论(0编辑  收藏  举报