zhjh
zhjh

Reputation: 61

Why Android Bluetooth receive lagging on certain devices

Recently when testing with the latest Samsung Tab A 8.0 (SM-T290) and Lenovo M7 (TB-7305F) (Both running Android v9), the bluetooth data being received is lagging when connected to certain devices. Running the same app on older tablets and phones connecting to same devices have no issues. Running the same app on some newer phones also have no issues.

It seems the InputStream on these devices with issues seems to buffer more data, instead of updating the socket read straight away. And tends to block for nearly the full BUFFER_SIZE. Where as on devices without issues, new data is returned nearly straight away.

Rough receive code as follows:

private static final int BUFFER_SIZE = 1024;
private OutputStream tx;
private InputStream rx;
private BluetoothSocket bt_socket;

public void run() {

    BluetoothDevice device = getDevice();
    if (device != null) {
        // create socket
        try {
            bt_socket = device.createInsecureRfcommSocketToServiceRecord(UUID_BLUETOOTH_SERIAL);

            bt_socket.connect();

            tx = bt_socket.getOutputStream();
            rx = bt_socket.getInputStream();

            nativeBluetoothStatusNotify(deviceName, FLAG_CONNECTED);
        } catch (IOException e) {

            try {
                bt_socket.close();
            } catch (IOException closeException) {
            }
            nativeBluetoothStatusNotify(deviceName, FLAG_CONNECTION_FAILED);
        }

        try {
            while (true) {
                int bytesRead = rx.read(buffer, 0, BUFFER_SIZE);
                String cOut = new String(buffer, 0, bytesRead, "ISO-8859-1");
                nativeBluetoothRxNotify(deviceName, buffer, cOut.length());
            }
        } catch (IOException e) {
            nativeBluetoothStatusNotify(deviceName, FLAG_RECEIVE_FAILED);
        } catch (NullPointerException e) {
            nativeBluetoothStatusNotify(deviceName, FLAG_BLUETOOTH_FAILURE);
        }
    }
}

Reducing the BUFFER_SIZE does help quite a lot, but the data still comes in choppy and delayed.

Can anyone provide some insight on this or any work around? Is this something in Android itself, my implementation or the underlying bluetooth firmware?

Upvotes: 3

Views: 449

Answers (1)

zhjh
zhjh

Reputation: 61

I ended up solving this issue by simply making sure I was sending data occasionally to those devices, instead of configuring on startup then just sitting receiving. A single heartbeat char (linefeed) every 500ms seemed the most basic fix which addressed the issue.

I suspect those tablets with issues must go into some bluetooth scan/advertise mode, or maybe low power when not sending for a period of time; which slows down receiving.

Upvotes: 2

Related Questions