从Android到蓝牙实时流式传输数据的最佳做法

Dan*_*y Y 10 android bluetooth stream simblee

我有一个Android应用程序,将数据写入simblee蓝牙.

在我的代码下面:

public void sendData(String data) {
    Utils.addLog(TAG,"sending data : " + data);
    if (mSerialCharacterstic == null) {
        Utils.addLog(TAG,"serial characteristic not found yet!");
        return;
    }

    Utils.addLog(TAG,"starting write data...");
    mSerialCharacterstic.setValue(data);
    Utils.addLog(TAG,"writing : " + data);
//        mGatt.beginReliableWrite();
        mGatt.writeCharacteristic(mSerialCharacterstic);
    }
Run Code Online (Sandbox Code Playgroud)

/*******************/

    @Override
    public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {

            Utils.addLog(TAG,"onCharacteristicWrite : " + new String(characteristic.getValue()) + " status : " + status);

//            gatt.executeReliableWrite();

    Utils.addLog(TAG,"data written");
    super.onCharacteristicWrite(gatt, characteristic, status);
}
Run Code Online (Sandbox Code Playgroud)

一切正常,(可靠的写作由于某种原因不起作用,但那是另一个问题)

现在,如果我想要流数据(例如onTouch事件实时发送led灯)

与我合作的唯一解决方案是将数据保存到arraylist中,然后OnCharacteriticWrite发送下一个要发送的数据.

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
                Utils.addLog(TAG,"onCharacteristicWrite : " + new String(characteristic.getValue()) + " status : " + status);

//            gatt.executeReliableWrite();
            Utils.addLog(TAG,"data written");

            if (isStreaming && streamQueue.size() > 0) {
                streamQueue.remove(0);
                Utils.addLog(TAG,"item removed");
                Utils.addLog(TAG,"stream size : " + streamQueue.size());
                if (streamQueue.size() > 0) {
                    Utils.addLog(TAG,"streaming next item");
                    sendData(streamQueue.get(0));
                }
                else {
                    Utils.addLog(TAG,"no more items to stream");
                    didSendFirstSet = false;
                }
            }

            super.onCharacteristicWrite(gatt, characteristic, status);
        }
Run Code Online (Sandbox Code Playgroud)

这对我有用,但我确信必须有一种更可靠的方式来发送数据,我找不到任何适当的文档(在我的代码中,在流式传输期间发生的任何错误都会停止整个流)