蓝牙socket读取数据需读累次才读全
今天上班解决了一个问题:android程序通过蓝牙socket读取数据时,需要读多次才能把完整的响应APDU读全。当前用的方法来自android示例程序:
<!--EndFragment-->public void run() { Log.i(TAG, "BEGIN mConnectedThread"); byte[] buffer = new byte[1024]; int bytes; // Keep listening to the InputStream while connected while (true) { try { // Read from the InputStream Log.i(TAG, "Read from the InputStream..."); bytes = mmInStream.read(buffer); Log.i(TAG, "Read from the InputStream, length is "+bytes); // Send the obtained bytes to the UI Activity mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { Log.e(TAG, "disconnected", e); connectionLost(); break; } } }
响应APDU是
02001580FFFFFFFF00A4040010D15600010180038000000001000000006A03,
接收三次,每次的结果都不一样:
(1)02001580FFFFFFFF00A4040010D1560001018003 8000000001000000006A 03
(2)02 001580FFFFFFFF00A4040010D15600010180038000000001000000006A 03
(3)02001580FFFFFFFF00A4040010D15600010180038000000001000000006A 03
修改示例代码:响应APDU是可以解析的,第3个字节的值加上10就等于响应APDU的长度,其中10是前缀和后缀的长度之和。
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
// int bytes;
int len = 0;
int i = 0;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
Log.i(TAG, "Read from the InputStream...");
// bytes = mmInStream.read(buffer);
buffer[i++] = (byte) mmInStream.read();
if (i == 3) {
len = buffer[2] + 10;
}
Log.i(TAG, "Read from the InputStream, data is "
+ buffer[i - 1]);
if (i == len) {
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, len,
-1, buffer).sendToTarget();
len = 0;
i = 0;
}
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
255不就够啦