sendNotification

fun sendNotification(characteristicUUID: UUID, value: ByteArray): Boolean

Sends a notification to all connected devices that have enabled notifications for the specified characteristic.

This method broadcasts a characteristic value change to all subscribed central devices. A device is considered subscribed when it has written BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE to the characteristic's Client Characteristic Configuration Descriptor (CCCD).

How Notifications Work

  1. The central device subscribes by writing to the CCCD

  2. The peripheral (this server) stores the subscription in notificationEnabledDevices

  3. When data changes, call this method to push the update to all subscribers

  4. Each subscribed device receives the new value without needing to poll

Value Storage

The provided value is automatically stored in characteristicValues, so subsequent read requests from centrals will return this same value.

Example: Sending Heart Rate Updates

val heartRateMeasurementUUID = UUID.fromString("00002A37-0000-1000-8000-00805f9b34fb")

// Heart Rate Measurement format: [Flags, Heart Rate Value]
// Flags = 0x00 means heart rate is in UINT8 format
fun sendHeartRate(bpm: Int) {
val value = byteArrayOf(
0x00, // Flags: Heart Rate Value Format is UINT8
bpm.toByte() // Heart Rate Measurement Value
)

val sent = gattServer.sendNotification(heartRateMeasurementUUID, value)
if (sent) {
Log.d(TAG, "Heart rate $bpm sent to subscribers")
} else {
Log.w(TAG, "No subscribers for heart rate notifications")
}
}

// Start a periodic update
lifecycleScope.launch {
while (isActive) {
sendHeartRate(Random.nextInt(60, 100))
delay(1000) // Send every second
}
}

Error Handling

The method handles individual device failures gracefully:

  • If one device fails, notifications are still attempted for other devices

  • Exceptions are caught and logged, not propagated

  • Returns true if at least one notification succeeded

Return

true if the notification was successfully sent to at least one device, false if: - The GATT server is not running - The characteristic UUID was not found in any service - No devices have enabled notifications for this characteristic - All notification attempts failed

Parameters

characteristicUUID

The UUID of the characteristic whose value has changed. Must match a characteristic that exists in one of the server's services.

value

The new characteristic value to send. Maximum length depends on the negotiated MTU (typically 20 bytes for default MTU of 23, or up to 512 bytes for larger MTUs).

See also

BleGattServer.notificationEnabledDevices

Throws

if BLUETOOTH_CONNECT permission is not granted (API 31+)