Short answer: request a larger MTU, split your data into chunks of (MTU minus 3) bytes, send them with write without response, and wait for the stack to be ready before each next chunk. If the MTU stays at the default 23, your chunk size is 20 bytes.
1. Negotiate the MTU
gatt.requestMtu(247)
override fun onMtuChanged(gatt: BluetoothGatt, mtu: Int, status: Int) {
if (status == BluetoothGatt.GATT_SUCCESS) chunkSize = mtu - 3
}
Start with chunkSize = 20 so you are safe if negotiation fails or the device refuses.
2. Split the payload
fun chunks(data: ByteArray, size: Int): List<ByteArray> =
data.toList().chunked(size).map { it.toByteArray() }
3. Send without response
Write without response is much faster than write with response, because it does not wait for a confirmation per packet. Check the characteristic supports PROPERTY_WRITE_NO_RESPONSE first.
// Android 13+ (API 33)
val code = gatt.writeCharacteristic(
characteristic, chunk,
BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
)
if (code != BluetoothStatusCodes.SUCCESS) { /* retry shortly */ }
If the call reports the stack is busy, wait a few milliseconds and retry the same chunk instead of skipping it. On Android 12 and lower, set the write type and value on the characteristic and call the older writeCharacteristic(characteristic), which returns a boolean.
4. Add your own integrity
Without per-packet confirmation, include a length and a checksum (CRC) in your protocol, and have the device reply once at the end with success or the sequence number to resend from.
Common mistakes
- Sending chunks larger than the real MTU allows.
- Firing chunks in a tight loop with no back-pressure.
- Mixing other GATT operations into the middle of a transfer.
FAQ
What chunk size should I use?
MTU minus 3 bytes, or 20 bytes if the MTU is the default 23.
Is write without response reliable?
Not by itself. Add sequence numbers or a checksum and an end-of-transfer acknowledgement.
Related: Android BLE Connection Problems: 7 Mistakes and Fixes.