Android Bluetooth sending concatenated data at once

╄→гoц情女王★ 提交于 2020-01-25 20:59:11

问题


I am using Bluetooth Chat App code to transfer data between two android device. But the code is sending concatenated data. For example: When I try to send data like below:

  1. a
  2. b
  3. c
  4. d

It sometime send data in this form:

  1. a
  2. bc
  3. d

Here is my write code for sending data:

public synchronized void write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);

            mHandler.obtainMessage(BluetoothHelper.MESSAGE_WRITE, -1, -1, buffer)
                    .sendToTarget();
            mmOutStream.flush();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

Also my read code is:

if (mmInStream.available()>0){
                    bytes = mmInStream.read(buffer);
                    mHandler.obtainMessage(BluetoothHelper.MESSAGE_READ, bytes, -1, buffer)
                            .sendToTarget();
                }else {
                    SystemClock.sleep(100);
                }

I tried flush and sleep but they dont fix problem. Please help.


回答1:


The concatenation is taking place due to difference in execution speed of two different threads.

One is the UI thread (you android application), i.e. where the data received over Bluetooth is being viewed. The UI thread refresh is by following line.

mHandler.obtainMessage(BluetoothHelper.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();

And the second thread is the one collecting the data being received over Bluetooth link. the code receiving the data over Bluetooth is:

mmInStream.read(buffer);

This is a blocking call, i.e. returns only when something is received over Bluetooth.

The UI thread is refreshing the view comparatively slowly than the data being received over Bluetooth thread. It means by the time UI view is refreshed next time, more than one characters may have already received on BT reading thread. Hence it appears the data is concatenated. And this concatenation will be at random times and with random number characters being concatenated.

To resolve this issue:

1) While transmitting : Transmit character (or a packet) followed by a delimiter character.

2) And while receiving : Send the message to UI only after concluding that a character (or a packet) followed by a delimiter is received. That means you will have to accumulate the receiving characters and verify these accumulated buffer each time after the blocking call mmOutStream.write(buffer) returns.

Have a look at this question and answer provided therein.



来源:https://stackoverflow.com/questions/31156547/android-bluetooth-sending-concatenated-data-at-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!