蓝牙socket读取数据需读多次才读全
16lz
2021-01-26
今天上班解决了一个问题: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 connectedwhile (true) {try {// Read from the InputStreamLog.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 ActivitymHandler.obtainMessage(BluetoothChat.MESSAGE_READ, len,-1, buffer).sendToTarget();len = 0;i = 0;}} catch (IOException e) {Log.e(TAG, "disconnected", e);connectionLost();break;}}}
更多相关文章
- Android(安卓)— 使用 SharedPreferences 本地保存 key-value 数
- Android轻松实现多语言的方法示例
- 【Android】获得系统语言和地区
- Android(安卓)USB设备通信--读写操作
- Android(安卓)WebView详解(加速加载篇)
- Android(安卓)ApiDemos示例解析(129):Views->Layout Animation->
- Android的ImageSwitcher和TextSw-android学习之旅(三十四)
- Android向Web站点发送GET请求、POST请求