Skip to content

[Bug]: Android ≤ 12: a write issued just after a link loss on an autoConnect client is never completed, so after the auto-reconnect every write lags by one and times out #394

Closed

Description

@vienvudev

Library version

3.4.0 (also present on main: writeValue has no connection check)

Reproducible with the example app

Not tested

OS

Android

OS version

Android 11 (API 30), Samsung SC-02M. Likely affects API ≤ 32 only

Device connecting to

A commercial BLE peripheral driven by write-without-response to a vendor characteristic

BLE version of connecting device

Unknown

What happened?

With connect(autoConnect: true) on Android, the BluetoothGatt client stays open
after a link loss so that Android can reconnect it. If a write is submitted in the
few milliseconds after STATE_DISCONNECTED (for example, a periodic write from a
timer that has not yet seen the disconnect), that write is never completed, and
after the auto-reconnect every write times out:

  1. onConnectionStateChange(STATE_DISCONNECTED) removes the client from
    connectedGatts and runs cleanUpConnection(deviceId, gatt), which fails every
    pending write. close() is skipped because the device is in autoConnectDevices.
  2. 30 ms later writeValue is called. gattRegistry.get(deviceId) still returns the
    open client and getCharacteristic() still finds the cached characteristic. The
    WriteResultFuture is registered. Below API 33 the plugin uses the deprecated
    writeCharacteristic(characteristic), which returns true once the request is
    handed to GattService. So the plugin counts it as success and keeps the future.
  3. GattService then drops the request. The system logs
    E/BtGatt.GattService: writeCharacteristic() - No connection for …
    6 ms later, and onCharacteristicWrite is never called. Nothing removes the future
    afterwards: cleanup already ran, STATE_CONNECTED sweeps nothing, and the Dart
    timeout (10 s) does not withdraw the native entry.
  4. Android reconnects the same client (clientIf unchanged), and services are
    discovered again. From then on, the stack reports every write as successful within
    3–5 ms (onWriteCharacteristic() status=0), yet every Dart write times out after
    exactly 10 s. onCharacteristicWrite completes the oldest matching
    WriteResultFuture (firstOrNull, it.gatt === gatt), which is the stale one
    from step 2, so each write is completed by the next one's callback. With the
    per-device queue the peripheral gets about one write per 10 s until the
    device is disconnected.

This is the "lags by one" failure from #387 / #390, with a different trigger. Here
the stale entry comes from a write the stack accepted and then dropped, not one
that threw, so the #390 withdrawal does not apply. #376 does not help either, because
the reconnect reuses the same BluetoothGatt instance, so the ownership check matches.

Scope: likely API ≤ 32 only. On API 33+ the plugin calls
writeCharacteristic(characteristic, value, writeType), which returns a status code.
As far as I can tell from AOSP, GattService returns ERROR_DEVICE_NOT_CONNECTED
there, so the existing result != GATT_SUCCESS branch should fail the write right
away. I could not test this on API 33+.

Expected: a write submitted while the client is not connected fails right away with
deviceDisconnected, as Apple already does since #378. Writes after the auto-reconnect
complete normally.

For comparison: flutter_blue_plus (Android 7.0.x) keeps the client in a separate
autoConnect map but refuses a write unless the device is in its connected-devices map
(mConnectedDevices.get(remoteId) == null → "device is disconnected"). It removes
the device from that map on STATE_DISCONNECTED even when autoConnect keeps the
client open. So the same race fails fast there.

Possible fix (Android)

  • In writeValue, check connectedGatts.contains(gatt) inside
    synchronized(writeResultFutureList), right before the future is added, and fail with
    DEVICE_DISCONNECTED if it is missing. A check before taking the lock still leaves a
    gap: the check passes, then STATE_DISCONNECTED runs cleanup on the binder thread,
    and only then is the future added. Inside the lock it is safe, because
    onConnectionStateChange removes the client from connectedGatts before
    cleanUpConnection takes that lock. Either the check fails, or the future is added
    in time to be swept. The same likely applies to writeDescriptorValue and the read
    paths.
  • As a backstop, on STATE_CONNECTED fail any pending operations whose
    it.gatt === gatt, that is, ones left over from that client's previous link. Only
    that client's operations, not every operation for the address.

Workaround (app side, verified)

As soon as an unexpected disconnect is reported, call
UniversalBle.disconnect(deviceId), then connect(deviceId, autoConnect: true)
again, instead of letting Android reconnect the old client. disconnect() runs
cleanConnection → cleanUpConnection, which fails anything still pending on the old
client, and removes it from the registry. The new client starts with no stale
entries. Doing it straight away matters: if Android relinks the old client first, the
reset tears down a link that has just come back.

Verified on three power cycles:

  • With the reset delayed by about 1 s, the racing write reached the stack
    (No connection for …) and was then failed by the reset with
    deviceDisconnected.
  • With the reset started 25–85 ms after the link loss, the racing write arrived after
    the old client had left the registry and failed at once with deviceNotFound. It
    never reached the stack.
  • In every case, writes after the reconnect completed in 1–3 ms with no timeouts, the
    old client was closed by the plugin's fallback timer, and the peripheral was still
    discoverable after an intended disconnect.

The workaround costs a fresh connectGatt per link loss, and app code that relies on
the plugin's in-place autoConnect reconnect has to manage the reconnect itself.

Notes on logs

UniversalBle.setLogLevel(BleLogLevel.debug) plus the system BtGatt.GattService
lines. MAC and vendor UUIDs are redacted.

Before the power cycle, the same writes completed in about 10–25 ms each. The behaviour
reproduced on two separate power cycles. With the workaround above it did not occur
in three more power cycles (see Workaround).

Sample code

// Android ≤ 12, a peripheral with a write-without-response characteristic.
await UniversalBle.connect(deviceId, autoConnect: true);
await UniversalBle.discoverServices(deviceId);

// Write periodically, like a vibration pattern.
Timer.periodic(const Duration(milliseconds: 250), (_) {
  UniversalBle.write(deviceId, serviceId, charId, payload, withoutResponse: true)
      .catchError((e) => print(e));
});

// Power the peripheral off for about 5 s, then back on. Android reconnects the
// autoConnect client and discoverServices runs again on CONNECTED. From then on,
// every write fails with TimeoutException after 10 s.

Logs / stack trace

07:14:49.851 D/UniversalBle: WRITE -> XX:XX:XX:XX:87:96 <svc> <chr> len=12 property=WITHOUT_RESPONSE
07:14:49.857 D/BtGatt.GattService: onWriteCharacteristic() - address=…, status=0
07:14:49.918 D/BtGatt.GattService: onDisconnected() - clientIf=10, connId=10, status=19
07:14:49.928 D/UniversalBle: onConnectionStateChange-> Status: 19 Remote User Terminated Connection, NewState: 0
07:14:49.957 D/UniversalBle: WRITE -> XX:XX:XX:XX:87:96 <svc> <chr> len=12 property=WITHOUT_RESPONSE   <-- after cleanup
07:14:49.963 E/BtGatt.GattService: writeCharacteristic() - No connection for …                       <-- dropped, no callback
07:14:59.979 I/flutter: TimeoutException after 0:00:10.000000: Future not completed
07:15:00.427 D/UniversalBle: onConnectionStateChange-> Status: 0 null, NewState: 2                   <-- same clientIf=10
07:15:01.186 D/BluetoothGatt: onSearchComplete() Status=0
07:15:02.036 D/UniversalBle: WRITE -> …
07:15:02.040 D/BtGatt.GattService: onWriteCharacteristic() - address=…, status=0                    <-- stack completes in 4 ms
07:15:12.042 I/flutter: TimeoutException after 0:00:10.000000: Future not completed                  <-- Dart still times out
07:15:12.044 D/UniversalBle: WRITE -> …
07:15:12.055 D/BtGatt.GattService: onWriteCharacteristic() - address=…, status=0
07:15:22.048 I/flutter: TimeoutException after 0:00:10.000000: Future not completed
… continues, one write per 10 s

Activity

  1. added
    bug
    on Nov 21, 2026
  2. fotiDim commented on Nov 22, 2026

    @fotiDim
    Contributor

    @vienvudev please try #395

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions