Alex MitrovicBLE & IoT app developer, Android and iOS

Connections

Why your Android BLE app needs a GATT operation queue (and how to write one in Kotlin)

Android's BluetoothGatt runs one operation at a time, so a second one fails. Why that makes BLE apps flaky, and a Kotlin coroutine queue that fixes it.

Short answer

Android's BluetoothGatt can run only one GATT operation at a time per connection: a read, write, descriptor write, MTU request or service discovery started before the previous callback arrived fails (false, or ERROR_GATT_WRITE_REQUEST_BUSY on Android 13+) or is silently lost. A queue that sends one operation, waits for its callback with a timeout and only then sends the next removes a whole class of flaky bugs.

Key takeaways

  • One operation in flight per BluetoothGatt, always. Wait for the callback before the next one.
  • Enabling notifications is two steps: setCharacteristicNotification() and a CCCD descriptor write, which is a queued operation.
  • Give every operation a timeout, and fail everything queued when the connection drops.
  • Never block or do heavy work on the BluetoothGattCallback thread.
  • Use Android 13's new write methods: they return a status code instead of a boolean that hides “busy”.

If your BLE app works most of the time, fails “sometimes” on connect, and gets worse when you add a feature, look for the missing queue before anything else. It's the single most common structural problem I find in audits.

Why does Android need a GATT queue?

BluetoothGatt lets each connection have one pending GATT operation. Call writeCharacteristic while a discoverServices or a previous write is still running, and the call fails. Before Android 13 it returns false, which most code ignores. On Android 13+, the new writeCharacteristic(characteristic, value, writeType) returns an Int, and you'll see ERROR_GATT_WRITE_REQUEST_BUSY (201). Either way the write never happened.

That's why the bug is timing-dependent. On a fast phone with a fast device, operations happen to finish before the next starts. On a slower phone, or with one more notification to enable, they overlap.

Which calls count as an operation?

Everything that ends in a BluetoothGattCallback method: discoverServices, readCharacteristic, writeCharacteristic (with or without response), readDescriptor, writeDescriptor, requestMtu, readRemoteRssi, readPhy and setPreferredPhy. setCharacteristicNotification is local and doesn't need queuing, but the CCCD descriptor write that must follow it does.

Writes without response are a special case: Android still calls onCharacteristicWrite for them, when the packet has been handed to the controller. Waiting for that callback is your flow control; skip it and fast writes overflow the buffers.

A queue in Kotlin coroutines

A Mutex serializes operations, and each operation suspends until its callback completes a CompletableDeferred. A timeout protects you against callbacks that never come:

GattQueue.kt
class GattQueue(private val timeoutMs: Long = 5_000) {
    private val mutex = Mutex()
    private var pending: CompletableDeferred<GattResult>? = null

    /** Runs [start] only when no other operation is in flight, then waits for its callback. */
    suspend fun <T> run(name: String, start: () -> Boolean, map: (GattResult) -> T): T =
        mutex.withLock {
            val done = CompletableDeferred<GattResult>()
            pending = done
            try {
                if (!start()) throw GattException("$name could not start")
                val result = withTimeout(timeoutMs) { done.await() }
                if (result.status != BluetoothGatt.GATT_SUCCESS) throw GattException("$name failed", result.status)
                map(result)
            } finally {
                pending = null
            }
        }

    /** Call from every BluetoothGattCallback method that ends an operation. */
    fun complete(result: GattResult) { pending?.complete(result) }

    /** Call on disconnect: whatever was waiting fails now instead of timing out. */
    fun failAll(status: Int) { pending?.complete(GattResult(status)) }
}

data class GattResult(val status: Int, val value: ByteArray? = null)
class GattException(message: String, val status: Int = -1) : IOException(message)

Using it, enabling a notification becomes two lines that can't overlap with anything else:

Enabling notifications through the queue
@SuppressLint("MissingPermission")
suspend fun enableNotifications(gatt: BluetoothGatt, char: BluetoothGattCharacteristic) {
    check(gatt.setCharacteristicNotification(char, true)) // local, not queued
    val cccd = char.getDescriptor(CCCD_UUID)               // 0x2902
    queue.run("enable ${char.uuid}", start = {
        if (Build.VERSION.SDK_INT >= 33)
            gatt.writeDescriptor(cccd, BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE) == BluetoothStatusCodes.SUCCESS
        else @Suppress("DEPRECATION") run {
            cccd.value = BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
            gatt.writeDescriptor(cccd)
        }
    }) { }
}

And in the callback, every operation-ending method calls queue.complete(...), while onConnectionStateChange with STATE_DISCONNECTED calls queue.failAll(status).

Rules around the queue

  • One queue per connection, created with the BluetoothGatt and dropped when you close() it.
  • Don't block the callback thread. Callbacks arrive on a Binder thread. Complete the deferred and return; parse data elsewhere.
  • Copy values on Android 12 and lower. The deprecated callbacks hand you the characteristic object, whose value can change by the time you read it. Copy the bytes in the callback, or use the Android 13 callbacks that pass the value.
  • Notifications aren't operations. They arrive in onCharacteristicChanged at any time; send them to a SharedFlow, not through the queue.
  • Prioritize sparingly. A user action may need to jump ahead of a bulk transfer; split the transfer into chunks so it yields between them.

Libraries such as Nordic's Android-BLE-Library implement this pattern for you; if you use one, the queue is already there. The point is that something must own it. More on structuring the whole BLE layer in Kotlin Multiplatform for BLE apps.

FAQ

Why does BluetoothGatt.writeCharacteristic return false?

Most often because another GATT operation on the same connection is still in progress: Android allows one at a time. It also returns false if the characteristic doesn't support the write type or the connection is gone. Queue your operations and wait for each callback.

Can I write multiple BLE characteristics at the same time on Android?

Not on one connection. BluetoothGatt runs one operation at a time, so writes must be queued. Writes without response can go fast, but you still wait for each onCharacteristicWrite before sending the next.

Does iOS need a GATT operation queue?

Less than Android: CoreBluetooth queues requests internally. You still need to order the flow, for example finish discovery before subscribing, and respect canSendWriteWithoutResponse for fast writes.

Sources

Seeing this in your own app?

Send me the phone models and what the logs say. On a short call I'll tell you where I'd look first.

Book a free call

Free · NDA on request · reply within 1–2 working days