安卓经典蓝牙数据通信

1 前言

  在之前的文章中我们已经实现了手机端与设备的连接过程。接下来将继续学习如何与设备进行数据收发。

2 通信线程ReadThread

  经典蓝牙通信需要启动线程进行数据的读写,首先我们创建一个专门用于通信的线程ReadThread。ReadThread核心代码如下:

private class ReadThread extends Thread {

        public void run() {
            Log.e("TAG", "开启通信线程");
            byte[] buffer = new byte[1024];
            int bytes;
            in = null;
            try {
                //获取输入输出流,用于数据读写
                in  = socket.getInputStream();
                out = socket.getOutputStream();
            } catch (Exception e) {
                Log.e("TAG", "获取流出错");
            }           
            while (isReading) {
                try {
                    if ((bytes = in.read(buffer)) > 0) {

                        //将读取到的数据值存储到rece数组中
                        byte[] rece = new byte[bytes];
                        for(int i = 0; i < rece.length; i++){
                            rece[i] = buffer[i]
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    try {
                        Log.e("关闭流", "");
                        in.close();
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }

                    break;
                }
            }

            Log.e(TAG, "DataRead线程关闭");
        }
    }

  socket对象为ClientThread中createRfcommSocketToServiceRecord()方法返回的BluetoothSocket对象。

top Created with Sketch.