蓝牙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;
		}
	}
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值