Bluetooth Low Energy (BLE) is one of the most important technologies for building connected Android applications.
Modern BLE peripherals can transmit heart rate measurements, temperature readings, battery information, environmental data, and custom IoT sensor values directly to smartphones.
But receiving raw Bluetooth data is only the beginning.
A useful IoT application must transform that data into meaningful information through a responsive interface, real-time visualizations, connection status indicators, and historical records.
In this tutorial, we’ll build an Android BLE IoT Sensor Dashboard using Kotlin, Jetpack Compose, BluetoothGatt, StateFlow, and Room Database.
Our application will connect to compatible BLE peripherals, subscribe to sensor notifications, decode characteristic values, display real-time measurements, and save readings for historical analysis.
We’ll also explore Bluetooth SIG standard services, custom sensor protocols, connection management, performance optimization, and production-ready MVVM architecture.
1. What Is an IoT Sensor Dashboard?
An IoT sensor dashboard is an application that collects measurements from connected hardware and presents them through a visual interface.
Examples include:
- Heart rate monitoring
- Temperature monitoring
- Battery status tracking
- Environmental monitoring
- Smart-home sensor dashboards
- Industrial equipment monitoring
- Fitness device monitoring
- Wearable device companion apps
Our application will focus on three measurements:
Heart rate: Beats per minute (BPM).
Temperature: Degrees Celsius (°C).
Battery level: Percentage (%).
The architecture can later be extended to humidity, pressure, motion, and custom sensor data.
2. Why Use Bluetooth Low Energy?
BLE is designed for relatively low-power communication between nearby devices.
It is particularly suitable for battery-powered sensors.
Advantages include:
- Low-power wireless communication
- Support for standard GATT services
- Real-time characteristic notifications
- Compatibility with Android’s native Bluetooth APIs
- No internet requirement for local communication
- Support for many types of connected peripherals
However, BLE does not guarantee that every peripheral exposes the same services or data format.
Your application must understand the protocol implemented by the target hardware.
3. How Our Application Works
The dashboard follows this communication flow:
BLE Sensor Peripheral
|
v
Bluetooth Advertisement
|
v
Android BLE Scanner
|
v
GATT Connection
|
v
Service Discovery
|
+-- Heart Rate Service
|
+-- Health Thermometer Service
|
+-- Battery Service
|
v
Characteristic Read / Notify
|
v
Sensor Data Decoder
|
v
BLE Repository
|
+-- StateFlow
|
+-- Room Database
|
v
Jetpack Compose Dashboard
|
+-- Live Sensor Cards
|
+-- Trend Charts
|
+-- Connection Status
|
+-- Reading History
The Bluetooth layer handles communication.
The domain layer decodes measurements.
The repository coordinates sensor streams and persistence.
The ViewModel exposes application state.
Jetpack Compose renders the dashboard.
4. What We’ll Build
Our application will include:
- BLE device discovery.
- Nearby device listing.
- GATT connection management.
- Automatic service discovery.
- Heart rate measurement monitoring.
- Temperature measurement monitoring.
- Battery level monitoring.
- Real-time sensor cards.
- Heart rate trend chart.
- Temperature trend chart.
- Battery percentage indicator.
- Sensor connection status.
- Room Database history.
- Historical reading charts.
- Sensor data timestamps.
- Connection error handling.
- Reconnection controls.
- Dark and light themes.
- Tablet-friendly layouts.
- Offline operation.
5. Understand BLE Sensor Services
Bluetooth SIG defines standard GATT services for certain sensor categories.
| Sensor | Service UUID | Characteristic UUID |
|---|---|---|
| Heart Rate | 0x180D | 0x2A37 — Heart Rate Measurement |
| Health Thermometer | 0x1809 | 0x2A1C — Temperature Measurement |
| Battery | 0x180F | 0x2A19 — Battery Level |
These UUIDs are standardized identifiers.
They can be expanded to full 128-bit UUIDs.
For example:
Heart Rate Service
0000180D-0000-1000-8000-00805F9B34FB
Important hardware consideration
A device may expose only one of these services.
For example, a fitness tracker may expose Heart Rate and Battery services but not the Health Thermometer service.
Some temperature sensors use the Environmental Sensing service or manufacturer-specific GATT characteristics instead.
Our dashboard must detect which services are actually available.
6. Recommended Technology Stack
| Technology | Responsibility |
|---|---|
| Kotlin | Android application logic |
| Jetpack Compose | Dashboard interface |
| BluetoothLeScanner | BLE device discovery |
| BluetoothGatt | Peripheral communication |
| BluetoothGattCallback | Connection and data events |
| Kotlin Coroutines | Asynchronous operations |
| StateFlow | Reactive sensor streams |
| Room Database | Historical readings |
| MVVM | Application architecture |
| Hilt | Dependency injection |
| Compose Canvas | Custom sensor charts |
| Material 3 | Visual components |
No backend is required for the basic application.
All BLE communication and history storage can remain on the Android device.
7. Create the Android Project
Create an Empty Activity project in Android Studio.
Recommended configuration:
Project Name:
BLE IoT Dashboard
Package Name:
com.moiks.bleiotdashboard
Language:
Kotlin
UI:
Jetpack Compose
Architecture:
MVVM
Minimum SDK:
26
Android BLE APIs support earlier Android versions, but API 26 is a reasonable baseline for this tutorial.
8. Configure Gradle Dependencies
Open app/build.gradle.kts.
dependencies {
// Compose
implementation(
"androidx.activity:activity-compose:<version>"
)
implementation(
"androidx.lifecycle:lifecycle-viewmodel-compose:<version>"
)
implementation(
"androidx.lifecycle:lifecycle-runtime-compose:<version>"
)
// Coroutines
implementation(
"org.jetbrains.kotlinx:kotlinx-coroutines-android:<version>"
)
// Room
implementation(
"androidx.room:room-runtime:<version>"
)
implementation(
"androidx.room:room-ktx:<version>"
)
ksp(
"androidx.room:room-compiler:<version>"
)
// Hilt
implementation(
"com.google.dagger:hilt-android:<version>"
)
ksp(
"com.google.dagger:hilt-compiler:<version>"
)
}
Replace version placeholders with compatible published versions.
Configure the KSP and Hilt Gradle plugins.
Bluetooth framework APIs do not require a separate dependency.
9. Configure Android Bluetooth Permissions
Android 12 introduced dedicated Nearby Devices permissions.
Add the following to AndroidManifest.xml:
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
<uses-permission
android:name="android.permission.BLUETOOTH"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_ADMIN"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
android:maxSdkVersion="30" />
<uses-permission
android:name="android.permission.BLUETOOTH_SCAN"
android:usesPermissionFlags="neverForLocation" />
<uses-permission
android:name="android.permission.BLUETOOTH_CONNECT" />
The neverForLocation declaration is appropriate only when the application does not derive physical location from Bluetooth scan results.
Android may filter certain BLE beacons when this flag is used.
Request the applicable permissions at runtime.
For Android 11 and earlier, BLE scanning generally requires location permission and location services to be enabled.
10. Create the Sensor Type Model
Represent supported sensors using an enum.
enum class SensorType {
HEART_RATE,
TEMPERATURE,
BATTERY
}
This allows us to use a consistent model across the Bluetooth, repository, and UI layers.
11. Create the Sensor Reading Model
data class SensorReading(
val sensorType: SensorType,
val value: Float,
val unit: String,
val timestamp: Long =
System.currentTimeMillis()
)
Examples:
SensorReading(
sensorType = SensorType.HEART_RATE,
value = 72f,
unit = "bpm"
)
SensorReading(
sensorType = SensorType.TEMPERATURE,
value = 25.4f,
unit = "°C"
)
SensorReading(
sensorType = SensorType.BATTERY,
value = 85f,
unit = "%"
)
This shared model simplifies charting and persistence.
For a multi-device application, add a stable device or session identifier.
12. Create Standard BLE UUID Constants
object BleSensorUuids {
private fun uuid16(
value: String
): UUID {
return UUID.fromString(
"0000$value-0000-1000-8000-00805F9B34FB"
)
}
val HEART_RATE_SERVICE =
uuid16("180D")
val HEART_RATE_MEASUREMENT =
uuid16("2A37")
val THERMOMETER_SERVICE =
uuid16("1809")
val TEMPERATURE_MEASUREMENT =
uuid16("2A1C")
val BATTERY_SERVICE =
uuid16("180F")
val BATTERY_LEVEL =
uuid16("2A19")
val CCCD =
uuid16("2902")
}
Centralizing UUIDs reduces mistakes and makes the code easier to maintain.
13. Discover Compatible BLE Devices
Use the scanning implementation from Article 95.
The discovery flow is:
Start BLE Scan
|
v
Receive Advertisements
|
v
Filter Devices
|
v
Display Nearby Devices
|
v
User Selects Peripheral
|
v
Connect GATT
You can optionally filter advertisements by service UUID.
However, not every peripheral advertises all its GATT services.
A service may exist even when its UUID is absent from the advertisement.
For a general-purpose scanner, allow users to discover and inspect nearby devices.
14. Connect to the BLE Peripheral
After selecting a device:
val gatt = device.connectGatt(
context,
false,
gattCallback
)
The connection result is asynchronous.
Wait for BluetoothGattCallback.onConnectionStateChange().
On Android 12 and later, verify BLUETOOTH_CONNECT permission before using protected GATT APIs.
15. Discover GATT Services
After a successful connection:
gatt.discoverServices()
Handle the callback:
override fun onServicesDiscovered(
gatt: BluetoothGatt,
status: Int
) {
if (
status == BluetoothGatt.GATT_SUCCESS
) {
val services =
gatt.services
// Identify supported sensor services.
}
}
Do not assume every connected device supports all three measurements.
16. Detect Available Sensors
fun findAvailableSensors(
gatt: BluetoothGatt
): Set<SensorType> {
val result =
mutableSetOf<SensorType>()
if (
gatt.getService(
BleSensorUuids.HEART_RATE_SERVICE
)?.getCharacteristic(
BleSensorUuids.HEART_RATE_MEASUREMENT
) != null
) {
result += SensorType.HEART_RATE
}
if (
gatt.getService(
BleSensorUuids.THERMOMETER_SERVICE
)?.getCharacteristic(
BleSensorUuids.TEMPERATURE_MEASUREMENT
) != null
) {
result += SensorType.TEMPERATURE
}
if (
gatt.getService(
BleSensorUuids.BATTERY_SERVICE
)?.getCharacteristic(
BleSensorUuids.BATTERY_LEVEL
) != null
) {
result += SensorType.BATTERY
}
return result
}
This checks whether the expected characteristics exist.
Before enabling a Read or Subscribe button, also inspect the characteristic properties.
17. Understand Heart Rate Measurement Data
The Heart Rate Measurement characteristic uses a binary format defined by the Bluetooth SIG.
The first byte contains flags.
The flags determine whether the heart rate is encoded as an 8-bit or 16-bit unsigned integer.
Other optional fields may contain sensor contact information, energy expenditure, and RR intervals.
Do not assume the entire payload contains only a single heart rate number.
18. Decode Heart Rate Measurements
fun decodeHeartRate(
data: ByteArray
): Int? {
if (data.size < 2) {
return null
}
val flags =
data[0].toInt() and 0xFF
val is16Bit =
flags and 0x01 != 0
return if (is16Bit) {
if (data.size < 3) {
null
} else {
val low =
data[1].toInt() and 0xFF
val high =
data[2].toInt() and 0xFF
low or (high shl 8)
}
} else {
data[1].toInt() and 0xFF
}
}
This function decodes the heart rate value.
It intentionally ignores optional fields.
Example
A measurement of 72 BPM may be represented by:
Flags: 0x00
Value: 0x48
0x48 is 72 in decimal.
19. Convert Heart Rate Data into a Sensor Reading
fun parseHeartRateReading(
data: ByteArray
): SensorReading? {
val bpm =
decodeHeartRate(data)
?: return null
return SensorReading(
sensorType =
SensorType.HEART_RATE,
value = bpm.toFloat(),
unit = "bpm"
)
}
The repository can now process heart rate measurements without exposing raw Bluetooth byte arrays to the UI.
20. Understand Temperature Measurement Data
The standard Health Thermometer Temperature Measurement characteristic uses an IEEE-11073 32-bit FLOAT representation.
Its payload includes:
- Flags.
- Temperature value.
- Optional timestamp.
- Optional temperature type.
The temperature may be expressed in Celsius or Fahrenheit, depending on the flags.
This differs from manufacturer-specific sensors, which may use signed integers, IEEE-754 floats, or custom binary structures.
21. Decode IEEE-11073 Temperature Values
An IEEE-11073 32-bit FLOAT consists of a signed 24-bit mantissa and a signed 8-bit base-10 exponent.
The value is:
Temperature = Mantissa × 10^Exponent
Create a decoder:
fun decodeIeee11073Float(
data: ByteArray,
offset: Int
): Float? {
if (data.size < offset + 4) {
return null
}
val b0 =
data[offset].toInt() and 0xFF
val b1 =
data[offset + 1].toInt() and 0xFF
val b2 =
data[offset + 2].toInt() and 0xFF
val rawMantissa =
b0 or
(b1 shl 8) or
(b2 shl 16)
val mantissa =
if (
rawMantissa and 0x800000 != 0
) {
rawMantissa or -0x1000000
} else {
rawMantissa
}
val exponent =
data[offset + 3].toInt()
// IEEE-11073 reserves special mantissa
// values for NaN and infinities.
if (
rawMantissa in
0x007FFFFE..0x00800002
) {
return null
}
return (
mantissa *
10.0.pow(exponent)
).toFloat()
}
This educational decoder handles ordinary finite values and rejects the reserved special-value range.
Production implementations should use a thoroughly tested IEEE-11073 decoder covering all reserved values and edge cases.
22. Parse the Temperature Measurement Characteristic
fun decodeTemperatureCelsius(
data: ByteArray
): Float? {
if (data.size < 5) {
return null
}
val flags =
data[0].toInt() and 0xFF
val fahrenheit =
flags and 0x01 != 0
val temperature =
decodeIeee11073Float(
data,
offset = 1
) ?: return null
return if (fahrenheit) {
(temperature - 32f) *
(5f / 9f)
} else {
temperature
}
}
This converts Fahrenheit values into Celsius for a consistent dashboard.
Important
The Health Thermometer characteristic is not the same as a generic environmental temperature characteristic.
For environmental sensors, consult the applicable Bluetooth SIG characteristic specification.
23. Create a Temperature Sensor Reading
fun parseTemperatureReading(
data: ByteArray
): SensorReading? {
val celsius =
decodeTemperatureCelsius(data)
?: return null
return SensorReading(
sensorType =
SensorType.TEMPERATURE,
value = celsius,
unit = "°C"
)
}
For custom IoT devices, replace the decoder with the manufacturer’s documented data format.
24. Understand Battery Level Data
The standard Battery Level characteristic commonly represents battery percentage as an unsigned 8-bit integer.
Typical values range from 0 to 100.
The characteristic may support reading, notifications, or other behaviors depending on the peripheral.
25. Decode Battery Level
fun decodeBatteryLevel(
data: ByteArray
): Int? {
if (data.isEmpty()) {
return null
}
val percentage =
data[0].toInt() and 0xFF
return percentage.takeIf {
it in 0..100
}
}
Create a reading:
fun parseBatteryReading(
data: ByteArray
): SensorReading? {
val level =
decodeBatteryLevel(data)
?: return null
return SensorReading(
sensorType =
SensorType.BATTERY,
value = level.toFloat(),
unit = "%"
)
}
26. Read Battery Level Using GATT
First locate the Battery Level characteristic.
val characteristic =
gatt.getService(
BleSensorUuids.BATTERY_SERVICE
)?.getCharacteristic(
BleSensorUuids.BATTERY_LEVEL
)
Check whether the characteristic supports reading:
val canRead =
characteristic != null &&
(
characteristic.properties and
BluetoothGattCharacteristic.PROPERTY_READ
) != 0
If supported, initiate the read:
if (canRead && characteristic != null) {
gatt.readCharacteristic(
characteristic
)
}
Wait for the GATT callback to obtain the result.
27. Handle Characteristic Read Results
On Android 13 and later, use the value-based callback:
override fun onCharacteristicRead(
gatt: BluetoothGatt,
characteristic:
BluetoothGattCharacteristic,
value: ByteArray,
status: Int
) {
if (
status != BluetoothGatt.GATT_SUCCESS
) {
return
}
if (
characteristic.uuid ==
BleSensorUuids.BATTERY_LEVEL
) {
val reading =
parseBatteryReading(value)
// Send reading to repository.
}
}
Implement the legacy callback for older Android versions.
The callback should forward parsed data to the repository rather than directly updating Compose UI.
28. Subscribe to Heart Rate Notifications
Heart rate sensors commonly provide measurements through notifications.
First locate the characteristic:
val characteristic =
gatt.getService(
BleSensorUuids.HEART_RATE_SERVICE
)?.getCharacteristic(
BleSensorUuids.HEART_RATE_MEASUREMENT
)
Verify that the characteristic supports notifications.
Then enable local notification delivery:
gatt.setCharacteristicNotification(
characteristic,
true
)
For typical GATT peripherals, you must also write the Client Characteristic Configuration Descriptor (CCCD).
29. Configure the CCCD
val descriptor =
characteristic.getDescriptor(
BleSensorUuids.CCCD
)
For a notification characteristic:
val enableValue =
BluetoothGattDescriptor
.ENABLE_NOTIFICATION_VALUE
On Android 13 and later:
if (
Build.VERSION.SDK_INT >= 33 &&
descriptor != null
) {
gatt.writeDescriptor(
descriptor,
enableValue
)
}
The descriptor write is asynchronous.
Wait for onDescriptorWrite() before considering the subscription complete.
For indication-only characteristics, use ENABLE_INDICATION_VALUE.
For Android 12 and earlier, implement the compatible legacy descriptor write method.
30. Handle Temperature Indications
The standard Health Thermometer Temperature Measurement characteristic uses indications.
Therefore, the subscription must check for:
BluetoothGattCharacteristic
.PROPERTY_INDICATE
Use:
BluetoothGattDescriptor
.ENABLE_INDICATION_VALUE
Why is this important?
Notifications and indications are not interchangeable.
Notifications do not require an acknowledgment at the GATT protocol level.
Indications include confirmation behavior.
The application must configure the correct characteristic property and CCCD value.
31. Receive Real-Time Sensor Updates
On Android 13 and later:
override fun onCharacteristicChanged(
gatt: BluetoothGatt,
characteristic:
BluetoothGattCharacteristic,
value: ByteArray
) {
val reading =
when (characteristic.uuid) {
BleSensorUuids
.HEART_RATE_MEASUREMENT ->
parseHeartRateReading(value)
BleSensorUuids
.TEMPERATURE_MEASUREMENT ->
parseTemperatureReading(value)
BleSensorUuids
.BATTERY_LEVEL ->
parseBatteryReading(value)
else -> null
}
reading?.let {
// Forward to sensor repository.
}
}
Use the legacy callback on older Android versions.
For devices exposing multiple services with potentially overlapping custom characteristic UUIDs, also verify the parent service and connected device identity.
32. Create the Sensor Repository Interface
interface SensorRepository {
val connectionState:
StateFlow<BleConnectionState>
val latestReadings:
StateFlow<Map<SensorType, SensorReading>>
val readingEvents:
Flow<SensorReading>
suspend fun connect(
device: BluetoothDevice
)
suspend fun disconnect()
suspend fun readBatteryLevel()
}
The repository owns the Bluetooth connection and exposes application-friendly data.
The UI should not depend on BluetoothGatt directly.
33. Publish Sensor Readings with StateFlow
private val _latestReadings =
MutableStateFlow<
Map<SensorType, SensorReading>
>(emptyMap())
val latestReadings =
_latestReadings.asStateFlow()
Update the latest value:
fun updateReading(
reading: SensorReading
) {
_latestReadings.update { current ->
current + (
reading.sensorType to reading
)
}
}
StateFlow is suitable for the latest dashboard state.
For recording every sensor event, use a separate event stream or a controlled persistence pipeline.
StateFlow can conflate intermediate updates, so it should not be treated as a lossless event log.
34. Create the Dashboard UI State
data class SensorDashboardUiState(
val connectionState:
BleConnectionState =
BleConnectionState.Disconnected,
val heartRate:
SensorReading? = null,
val temperature:
SensorReading? = null,
val battery:
SensorReading? = null,
val availableSensors:
Set<SensorType> =
emptySet(),
val errorMessage:
String? = null
)
Nullable values distinguish unavailable measurements from legitimate zero values.
For example, a missing heart rate reading should display --, not 0 BPM.
35. Create the Dashboard ViewModel
class SensorDashboardViewModel(
private val repository:
SensorRepository
) : ViewModel() {
val latestReadings =
repository.latestReadings
val connectionState =
repository.connectionState
fun disconnect() {
viewModelScope.launch {
repository.disconnect()
}
}
}
A complete ViewModel can combine the connection state, available services, and latest sensor readings into a single UI state.
Use lifecycle-aware StateFlow collection in Compose.
36. Design the IoT Dashboard
Our dashboard should present the most important measurements immediately.
Recommended layout:
+----------------------------------+
| IoT Sensor Dashboard |
| |
| Device: Smart Health Sensor |
| Status: Connected |
| |
| +------------------------------+ |
| | Heart Rate | |
| | | |
| | 72 BPM | |
| | | |
| | Live Heart Rate Chart | |
| +------------------------------+ |
| |
| +------------------------------+ |
| | Temperature | |
| | | |
| | 25.4 °C | |
| | | |
| | Temperature Trend | |
| +------------------------------+ |
| |
| +------------------------------+ |
| | Battery Level | |
| | | |
| | 85% | |
| | [████████░░] | |
| +------------------------------+ |
| |
| [ Devices ] [ History ] [ Settings]
+----------------------------------+
Use large numerical values, readable units, and clear connection indicators.
37. Create a Reusable Sensor Card
@Composable
fun SensorValueCard(
title: String,
value: String,
unit: String,
icon: ImageVector,
modifier: Modifier = Modifier
) {
ElevatedCard(
modifier = modifier
) {
Column(
modifier =
Modifier.padding(20.dp),
verticalArrangement =
Arrangement.spacedBy(12.dp)
) {
Row(
verticalAlignment =
Alignment.CenterVertically
) {
Icon(
imageVector = icon,
contentDescription = null
)
Spacer(
modifier =
Modifier.width(8.dp)
)
Text(
text = title,
style =
MaterialTheme.typography
.titleMedium
)
}
Row(
verticalAlignment =
Alignment.Bottom
) {
Text(
text = value,
style =
MaterialTheme.typography
.headlineLarge
)
Spacer(
modifier =
Modifier.width(6.dp)
)
Text(
text = unit
)
}
}
}
}
Use the same component for heart rate, temperature, and battery measurements.
38. Display Heart Rate
@Composable
fun HeartRateCard(
reading: SensorReading?
) {
SensorValueCard(
title = "Heart Rate",
value =
reading?.value
?.toInt()
?.toString()
?: "--",
unit = "BPM",
icon = Icons.Default.Favorite,
modifier =
Modifier.fillMaxWidth()
)
}
Avoid interpreting a heart rate value as a medical diagnosis.
A consumer IoT dashboard should clearly communicate that readings depend on the connected device’s accuracy and intended use.
39. Display Temperature
@Composable
fun TemperatureCard(
reading: SensorReading?
) {
SensorValueCard(
title = "Temperature",
value =
reading?.value
?.let {
"%.1f".format(it)
}
?: "--",
unit = "°C",
icon = Icons.Default.Thermostat,
modifier =
Modifier.fillMaxWidth()
)
}
If the app supports international users, use locale-aware number formatting.
Also distinguish ambient temperature from body temperature.
These measurements have different meanings and should not be combined into one unlabeled chart.
40. Display Battery Percentage
@Composable
fun BatteryLevelCard(
percentage: Int?
) {
ElevatedCard(
modifier =
Modifier.fillMaxWidth()
) {
Column(
modifier =
Modifier.padding(20.dp),
verticalArrangement =
Arrangement.spacedBy(12.dp)
) {
Text("Battery Level")
Text(
text =
percentage
?.let { "$it%" }
?: "--",
style =
MaterialTheme.typography
.headlineLarge
)
LinearProgressIndicator(
progress = {
(
(percentage ?: 0)
.coerceIn(0, 100)
) / 100f
},
modifier =
Modifier.fillMaxWidth()
)
}
}
}
When battery data is unavailable, consider hiding the progress bar rather than displaying zero.
41. Create a Real-Time Sensor Chart
Compose Canvas can render a lightweight line chart without requiring an external charting library.
@Composable
fun SensorLineChart(
values: List<Float>,
modifier: Modifier = Modifier
) {
Canvas(
modifier = modifier
.fillMaxWidth()
.height(180.dp)
) {
if (values.size < 2) {
return@Canvas
}
val minValue =
values.minOrNull() ?: 0f
val maxValue =
values.maxOrNull() ?: 1f
val range =
(maxValue - minValue)
.coerceAtLeast(1f)
val path = Path()
values.forEachIndexed {
index, value ->
val x =
index.toFloat() /
(values.size - 1) *
size.width
val y =
size.height -
(
(value - minValue) /
range
) * size.height
if (index == 0) {
path.moveTo(x, y)
} else {
path.lineTo(x, y)
}
}
drawPath(
path = path,
color = Color.Green,
style = Stroke(
width = 3.dp.toPx(),
cap = StrokeCap.Round,
join = PathJoin.Round
)
)
}
}
This example draws values at equal horizontal intervals.
For irregularly timed readings, use timestamps to calculate horizontal positions.
A production chart should also include axes, units, labels, and accessibility descriptions.
42. Maintain a Rolling Chart Buffer
For real-time dashboards, avoid retaining an unlimited number of readings in memory.
Use a fixed-size buffer.
class RollingSensorBuffer(
private val maxSize: Int = 60
) {
private val values =
ArrayDeque<Float>()
fun add(value: Float) {
if (values.size >= maxSize) {
values.removeFirst()
}
values.addLast(value)
}
fun snapshot(): List<Float> {
return values.toList()
}
}
This keeps chart rendering efficient.
For example, retain the latest 60 samples in memory while saving longer-term history separately.
43. Add Sensor History with Room Database
Create a Room entity.
@Entity(
tableName = "sensor_readings",
indices = [
Index(
value = [
"sensorType",
"timestamp"
]
)
]
)
data class SensorReadingEntity(
@PrimaryKey(
autoGenerate = true
)
val id: Long = 0,
val sensorType: String,
val value: Float,
val unit: String,
val timestamp: Long,
val deviceId: String
)
The deviceId field allows history to be associated with a specific peripheral.
For devices using rotating Bluetooth addresses, prefer a stable application-level identifier when available.
44. Create the Sensor History DAO
@Dao
interface SensorReadingDao {
@Insert
suspend fun insert(
reading: SensorReadingEntity
)
@Query(
"""
SELECT * FROM sensor_readings
WHERE sensorType = :type
AND deviceId = :deviceId
ORDER BY timestamp DESC
LIMIT :limit
"""
)
fun observeRecentReadings(
type: String,
deviceId: String,
limit: Int = 100
): Flow<List<SensorReadingEntity>>
@Query(
"""
DELETE FROM sensor_readings
WHERE timestamp < :cutoff
"""
)
suspend fun deleteOlderThan(
cutoff: Long
)
@Query(
"""
DELETE FROM sensor_readings
"""
)
suspend fun clearAll()
}
Room provides a reactive history stream through Flow.
45. Create the Room Database
@Database(
entities = [
SensorReadingEntity::class
],
version = 1,
exportSchema = true
)
abstract class SensorDatabase :
RoomDatabase() {
abstract fun sensorReadingDao():
SensorReadingDao
}
Initialize the database as a singleton or provide it through Hilt.
Room.databaseBuilder(
applicationContext,
SensorDatabase::class.java,
"sensor_database"
).build()
46. Save Sensor Readings
Create a persistence repository.
class SensorHistoryRepository(
private val dao: SensorReadingDao
) {
suspend fun save(
reading: SensorReading,
deviceId: String
) {
dao.insert(
SensorReadingEntity(
sensorType =
reading.sensorType.name,
value = reading.value,
unit = reading.unit,
timestamp =
reading.timestamp,
deviceId = deviceId
)
)
}
}
Do not perform database writes directly inside a Bluetooth callback.
Forward readings to a coroutine-based persistence pipeline.
For high-frequency sensors, use buffering and batch insertion where appropriate.
47. Design the History Screen
Recommended features:
- Sensor type selection.
- Time-range filters.
- Historical line charts.
- Minimum value.
- Maximum value.
- Average value.
- Measurement timestamps.
- Device identification.
- Clear-history action.
Suggested time ranges:
Last 15 Minutes
Last Hour
Last 24 Hours
Last 7 Days
Last 30 Days
For large datasets, aggregate readings into time buckets before rendering charts.
48. Calculate Sensor Statistics
data class SensorStatistics(
val minimum: Float,
val maximum: Float,
val average: Float
)
Calculate:
fun calculateStatistics(
values: List<Float>
): SensorStatistics? {
if (values.isEmpty()) {
return null
}
return SensorStatistics(
minimum =
values.minOrNull() ?: 0f,
maximum =
values.maxOrNull() ?: 0f,
average =
values.average().toFloat()
)
}
For irregular sampling, a simple arithmetic mean may not represent a time-weighted average.
Use appropriate aggregation when sample intervals vary significantly.
49. Handle Connection Interruptions
BLE connections may fail or disconnect because of:
- Peripheral moving out of range.
- Bluetooth being disabled.
- Peripheral battery depletion.
- Radio interference.
- Peripheral firmware issues.
- Connection timeouts.
- GATT operation failures.
The dashboard should distinguish:
Disconnected
Connecting
Discovering Services
Subscribing
Connected
Reconnecting
Error
Use clear connection indicators rather than assuming the presence of a recent reading means the device is still connected.
50. Implement a Reconnection Strategy
A basic retry policy might use increasing delays.
fun reconnectDelay(
attempt: Int
): Long {
val delays = listOf(
1000L,
2000L,
4000L,
8000L,
15000L
)
return delays[
attempt.coerceIn(
0,
delays.lastIndex
)
]
}
Recommended behavior
- Retry only when appropriate.
- Stop after a reasonable number of attempts.
- Respect user-requested disconnection.
- Avoid reconnecting indefinitely.
- Cancel retries when Bluetooth is disabled.
- Revalidate permissions.
- Rediscover services after reconnection.
- Reconfigure subscriptions after reconnecting.
For production, use a connection state machine rather than a simple infinite retry loop.
51. Serialize GATT Operations
GATT operations are asynchronous.
Reads, writes, and descriptor operations should be coordinated carefully.
Recommended sequence:
Connected
|
v
Discover Services
|
v
Read Battery Level
|
v
Wait for Read Callback
|
v
Enable Heart Rate Notifications
|
v
Wait for CCCD Write Callback
|
v
Enable Temperature Indications
|
v
Wait for CCCD Write Callback
|
v
Ready for Live Data
Do not initiate all operations simultaneously.
Use a dedicated operation queue with timeouts and callback-based completion.
52. Handle Missing Sensor Data
A peripheral may expose only some of the expected services.
Example:
Connected Device:
Fitness Band
Heart Rate: Available
Temperature: Not Supported
Battery: Available
The UI should clearly distinguish:
- Available and receiving data.
- Available but not yet reporting.
- Not supported.
- Disconnected.
- Measurement error.
Avoid displaying a fake zero value when a sensor is unavailable.
53. Add Stale Reading Detection
A connection can remain active while sensor notifications stop.
Track the timestamp of the latest reading.
fun isReadingStale(
reading: SensorReading?,
now: Long,
timeoutMillis: Long
): Boolean {
if (reading == null) {
return true
}
return now - reading.timestamp >
timeoutMillis
}
The stale threshold should depend on the sensor’s expected update frequency.
For example, a heart rate sensor may update frequently, while a temperature sensor may report only when its measurement changes.
Do not apply one universal timeout to every characteristic.
54. Support Multiple BLE Devices
A more advanced dashboard can combine data from multiple peripherals.
Example:
Heart Rate:
Fitness Band
Temperature:
Environmental Sensor
Battery:
Both Devices
A multi-device architecture should maintain separate:
- GATT connections.
- Connection states.
- Service discoveries.
- Operation queues.
- Notification subscriptions.
- Device identifiers.
- Sensor histories.
Avoid storing every peripheral’s state in a single global BluetoothGatt reference.
55. Optimize Battery Consumption
Recommended practices:
- Avoid unnecessary continuous scanning.
- Stop discovery after selecting a device.
- Prefer notifications over frequent polling.
- Avoid repeated battery-level reads.
- Reduce chart refresh frequency when possible.
- Batch historical database writes.
- Release unused connections.
- Avoid aggressive reconnection loops.
- Respect Android background execution limits.
The most efficient monitoring strategy depends on the peripheral’s reporting frequency and power requirements.
56. Background Monitoring Considerations
Continuous BLE monitoring while the application is in the background requires additional design.
Android places restrictions on background execution and foreground services.
For an application that genuinely needs ongoing connected-device communication, investigate the appropriate connected-device foreground service type and current Android requirements.
Depending on the use case, Android Companion Device APIs may provide a more suitable architecture.
Do not assume a ViewModel coroutine can keep a BLE connection active indefinitely after the application leaves the foreground.
57. Privacy and Security
Sensor measurements may reveal sensitive information about a person or their environment.
Recommended practices:
- Keep data on-device by default.
- Request only necessary Bluetooth permissions.
- Avoid uploading sensor readings without consent.
- Do not log private characteristic values.
- Validate incoming binary data.
- Use pairing or encryption where required.
- Protect locally stored history.
- Provide history deletion controls.
- Minimize device identifier retention.
- Explain what measurements are collected.
- Avoid presenting unvalidated sensor readings as medical diagnoses.
Important
A heart rate dashboard is not automatically a medical device.
If an application is intended for diagnosis, treatment, or clinical monitoring, additional regulatory, validation, and safety requirements may apply.
58. Recommended Project Structure
com.moiks.bleiotdashboard/
|
+-- ble/
| +-- BleScanner.kt
| +-- BleGattManager.kt
| +-- GattOperationQueue.kt
| +-- SensorSubscriptionManager.kt
|
+-- data/
| +-- decoder/
| | +-- HeartRateDecoder.kt
| | +-- TemperatureDecoder.kt
| | +-- BatteryDecoder.kt
| |
| +-- local/
| | +-- SensorDatabase.kt
| | +-- SensorReadingDao.kt
| | +-- SensorReadingEntity.kt
| |
| +-- repository/
| +-- SensorRepositoryImpl.kt
| +-- SensorHistoryRepository.kt
|
+-- domain/
| +-- model/
| | +-- SensorType.kt
| | +-- SensorReading.kt
| | +-- BleConnectionState.kt
| |
| +-- repository/
| | +-- SensorRepository.kt
| |
| +-- usecase/
| +-- ConnectSensorUseCase.kt
| +-- ObserveSensorUseCase.kt
| +-- SaveSensorReadingUseCase.kt
|
+-- presentation/
| +-- SensorDashboardViewModel.kt
| +-- SensorDashboardUiState.kt
| +-- SensorHistoryViewModel.kt
|
+-- ui/
| +-- DeviceScannerScreen.kt
| +-- SensorDashboardScreen.kt
| +-- SensorValueCard.kt
| +-- SensorLineChart.kt
| +-- SensorHistoryScreen.kt
| +-- ConnectionStatusCard.kt
|
+-- di/
| +-- BluetoothModule.kt
| +-- DatabaseModule.kt
|
+-- MainActivity.kt
This structure keeps Bluetooth communication, data decoding, persistence, and UI responsibilities separate.
59. Testing Strategy
| Test scenario | Expected result |
|---|---|
| BLE unavailable | Unsupported-device message |
| Bluetooth disabled | Enable request |
| Permissions denied | Helpful permission UI |
| BLE device discovery | Device appears |
| GATT connection | Connected state |
| Service discovery | Available sensors detected |
| Heart rate 8-bit | Correct BPM |
| Heart rate 16-bit | Correct BPM |
| Temperature Celsius | Correct value |
| Temperature Fahrenheit | Converted correctly |
| Invalid temperature data | Rejected safely |
| Battery 0–100 | Correct percentage |
| Invalid battery value | Rejected |
| Heart rate notifications | Live updates |
| Temperature indications | Live updates |
| CCCD write failure | Subscription error |
| Missing service | Unsupported state |
| Disconnection | UI updates |
| Reconnection | Services rediscovered |
| Stale reading | Stale indicator |
| History insertion | Reading saved |
| History chart | Correct values |
| Multiple devices | Data remains separated |
| Offline mode | Local monitoring works |
| Dark mode | UI remains readable |
| Tablet layout | Responsive dashboard |
Test with physical BLE peripherals.
Use known sample byte arrays for decoder unit tests.
60. Common Development Mistakes
Mistake 1: Assuming Every Device Exposes Standard Sensor Services
Many peripherals use proprietary protocols.
Mistake 2: Decoding Every Characteristic as UTF-8
Sensor data is often binary.
Mistake 3: Ignoring Heart Rate Flags
The value may use an 8-bit or 16-bit representation.
Mistake 4: Treating Temperature Data as a Simple Integer
Standard Health Thermometer measurements use IEEE-11073 encoding.
Mistake 5: Using Notifications for an Indication-Only Characteristic
Configure the correct CCCD value.
Mistake 6: Starting Multiple GATT Operations Simultaneously
Serialize operations.
Mistake 7: Updating Compose Directly from Bluetooth Callbacks
Use a repository and StateFlow.
Mistake 8: Writing Every High-Frequency Sample Individually Without Limits
Use buffering or batch persistence where appropriate.
Mistake 9: Treating Missing Sensor Data as Zero
Represent unavailable readings explicitly.
Mistake 10: Forgetting to Release BluetoothGatt
Close unused GATT clients.
Mistake 11: Reconnecting Without Rediscovering Services
Restore the required subscriptions after reconnection.
Mistake 12: Assuming Sensor Values Are Medically Accurate
Accuracy depends on the hardware, firmware, measurement conditions, and intended use.
61. Production Checklist
Before publishing:
- Android BLE permissions implemented.
- BLE hardware support checked.
- Bluetooth enable flow implemented.
- Device discovery implemented.
- GATT connection manager implemented.
- Service discovery implemented.
- Standard sensor UUIDs configured.
- Characteristic properties checked.
- Heart rate decoder tested.
- Temperature decoder tested.
- Battery decoder tested.
- Notifications configured.
- Indications configured.
- CCCD writes verified.
- GATT operation queue implemented.
- StateFlow sensor streams implemented.
- Real-time dashboard implemented.
- Sensor charts implemented.
- Room history implemented.
- Connection errors handled.
- Reconnection policy implemented.
- Stale readings identified.
- Sensitive sensor data protected.
- Battery consumption reviewed.
- Physical peripherals tested.
- Accessibility reviewed.
62. Frequently Asked Questions
What is an Android BLE IoT Sensor Dashboard?
It is an Android application that connects to BLE peripherals and displays measurements such as heart rate, temperature, and battery level.
Can I build an IoT dashboard with Kotlin?
Yes. Kotlin can access Android’s native BLE APIs and integrate with Jetpack Compose.
Can Jetpack Compose display live BLE data?
Yes. StateFlow can provide sensor updates that Compose renders reactively.
Does BLE require internet access?
No. Local BLE communication works without internet access.
Can I monitor heart rate through BLE?
Yes, when the peripheral exposes a compatible Heart Rate Measurement characteristic.
Can I monitor temperature through BLE?
Yes, when the peripheral exposes a compatible temperature characteristic and its data format is understood.
Can I read a BLE device’s battery level?
Yes, if the device exposes a readable Battery Level characteristic.
What is the Heart Rate Service UUID?
The standard Heart Rate Service UUID is 0x180D.
What is the Battery Service UUID?
The standard Battery Service UUID is 0x180F.
What is the Temperature Measurement characteristic UUID?
The Health Thermometer Temperature Measurement characteristic UUID is 0x2A1C.
Why are my sensor notifications not arriving?
Possible causes include incorrect characteristic properties, missing CCCD configuration, insufficient permissions, or peripheral-specific behavior.
Can I connect to multiple BLE sensors?
Yes, subject to Android device capabilities and connection limits.
Can I save BLE sensor history?
Yes. Room Database can store measurements locally.
Can I create real-time charts in Jetpack Compose?
Yes. Compose Canvas can draw custom charts, or you can use a compatible charting library.
Can I monitor sensors in the background?
Potentially, but continuous background communication requires compliance with Android’s background execution and foreground service requirements.
Are BLE sensor readings always accurate?
No. Accuracy depends on the sensor, calibration, measurement conditions, and device implementation.
Conclusion
Building an Android BLE IoT Sensor Dashboard is an excellent way to combine Bluetooth communication, reactive Kotlin architecture, local persistence, and modern UI development.
Using Kotlin, Jetpack Compose, BluetoothGatt, StateFlow, Room Database, and Compose Canvas, developers can build connected-device applications that display live measurements and historical trends.
The most important practices are:
- Understand the peripheral’s GATT protocol.
- Discover services and characteristics dynamically.
- Decode sensor data using the correct specification.
- Use notifications or indications where supported.
- Serialize GATT operations.
- Keep Bluetooth communication separate from UI logic.
- Expose live measurements through StateFlow.
- Store history using Room Database.
- Use efficient rolling buffers for charts.
- Handle missing and stale measurements.
- Implement controlled reconnection.
- Respect battery and background execution constraints.
- Protect sensitive sensor information.
- Test on physical BLE devices.
A production-quality IoT dashboard combines reliable BLE communication with accurate data decoding, responsive visualization, and robust lifecycle management.
This architecture provides a foundation for fitness wearables, smart-home dashboards, industrial monitoring tools, environmental sensors, and custom connected-device applications.
Official References
- Android Bluetooth Low Energy Overview
- Android Bluetooth Permissions
- Connect to a GATT Server
- Transfer BLE Data
- BluetoothGatt API
- BluetoothGattCallback API
- Bluetooth SIG Assigned Numbers
- Bluetooth SIG Specifications
- Jetpack Compose
- Room Database
- Android Architecture Guide
Published by Moiks Developer Blog — Practical tutorials covering Android, Kotlin, Jetpack Compose, Flutter, React Native, SwiftUI, and modern software engineering.