在安卓中从蓝牙设备读取数据

2022-09-03 07:09:04

我正在使用蓝牙聊天来连接和接收来自蓝牙设备的数据。

我使用以下代码来读取数据:

public void run() {
    byte[] buffer = new byte[1024];
    int bytes;
    Log.v("MR", "start listening....");

    // Keep listening to the InputStream while connected
    while (true) {
        try {
            // Read from the InputStream
            Log.d("MR", "buffer in try");

            bytes = mmInStream.read(buffer);
            Log.d("MR", "input stream :"+(new String(buffer)));
            // Send the obtained bytes to the UI Activity
            mHandler.obtainMessage(Conn.MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            Log.d("MR", "buffer after");

        } catch (Exception e) {
            Log.e("MR", "Error :"+e.getMessage());
            //
            connectionLost();
           // break;
        }

        Log.d("MR", "buffer after while");
    }
}

设备一直在不停地发送数据。

通过上面的代码,我得到的消息是:

Log.d("MR", "buffer in try");

然后它转到下一行:

bytes=mmInStream.read(buffer);

并且永远不会从该呼叫中返回。我想这是因为它开始从设备读取数据,并且在断开连接之前不会停止。如何一次读取一定数量的字节?

编辑

除非它由于无法从设备获取任何数据而保留在代码中?bytes = mmInStream.read(buffer);


答案 1

我使用DataInputStreams代替,因为你可以做一个readFully()方法,该方法在返回之前等待读取一定数量的字节。我像这样设置BT连接:

BluetoothDevice btDevice = bta.getRemoteDevice(macAddress);
BluetoothSocket btSocket = InsecureBluetooth.createRfcommSocketToServiceRecord(
                    btDevice, UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"), false);

btSocket.connect();
InputStream input = btSocket.getInputStream();
DataInputStream dinput = new DataInputStream(input);

然后后来当我想读的时候,我用readFully:

dinput.readFully(byteArray, 0, byteArray.length);

答案 2

推荐