我正在使用蓝牙聊天来连接和接收来自蓝牙设备的数据。
我使用以下代码来读取数据:
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);
代码,否则从设备上获取任何数据?
答案 0 :(得分:13)
我使用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);