Best practice to stream data in realtime from Android to Bluetooth

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-09 09:20:42

问题


I have an android application that writes data to a simblee bluetooth.

Below the code I have :

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);
    }

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

    @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);
}

Everything works correctly, (reliableWrite wasn't working for some reason but that's for another question)

Now if I want to stream data (for example onTouch event send the led to light in realtime)

The only solution that's working with me, is saving the data to stream in an arraylist, and OnCharacteriticWrite send the next data to send.

        @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);
        }

This is working for me, but I'm sure there must be a more reliable way to send the data nut I couldn't find any proper documentation for it (in my code any error that happens during streaming will stop the whole stream)

来源:https://stackoverflow.com/questions/47607479/best-practice-to-stream-data-in-realtime-from-android-to-bluetooth

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