Android Bluetooth Low Energy (BLE) & Permissions 📡
Working with IoT devices, Gatt Servers, and BLE scanning requires precise lifecycle control and permission handling.
⚡ When to Use
- When connecting to hardware devices via Bluetooth.
🏗️ Core Rules / Pillars
1. The Android 12+ Permission Shift
- Pattern: Location permissions are NO LONGER explicitly required for BLE if you declare that you are not using BLE for location tracking.
- Implementation: Use
BLUETOOTH_CONNECTandBLUETOOTH_SCANpermissions in the manifest, and optionally setandroid:usesPermissionFlags="neverForLocation"onBLUETOOTH_SCAN.
2. Reactive BLE Wrappers
- Pattern: The native
BluetoothGattCallbackis entirely callback-based and prone to race conditions if used directly. - Implementation: You MUST wrap BLE reads, writes, and connection states in Kotlin
callbackFlow { }orMutableStateFlowto guarantee state correctness across coroutines.
🚧 Critical Anti-Hallucination Guards
- Trap: NEVER fire multiple BLE GATT operations at exactly the same time. The Android BLE stack will drop packets quietly. Always queue GATT operations sequentially!