Short answer: to keep a BLE connection reliable while your app is not on screen, run the GATT logic inside a foreground service with the connectedDevice type and show a notification. On Android 14 and higher you must declare the type and its permission in the manifest.
Why a plain background connection fails
Android restricts background work. Without a foreground service, your process can be stopped and the connection dropped when the user leaves the app.
Manifest
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<service
android:name=".BleService"
android:foregroundServiceType="connectedDevice"
android:exported="false" />
Start the service in the foreground
class BleService : Service() {
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Connected to device")
.setSmallIcon(R.drawable.ic_bluetooth)
.build()
ServiceCompat.startForeground(
this, 1, notification,
ServiceInfo.FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
)
// connect GATT here
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? = null
}
Create the notification channel before starting, and request POST_NOTIFICATIONS on Android 13+ so the notification is visible.
Good practice
- Keep the GATT object and queue inside the service, not an Activity.
- Stop the service and call
gatt.close()when the user disconnects. - Tell the user clearly why the notification is shown.
- Check the current Play policy on foreground service types before release.
FAQ
Do I need a foreground service for BLE?
Only if the connection must continue when the app is not visible. For foreground-only use, no.
Which foreground service type for BLE?
connectedDevice is the usual type for a connected Bluetooth peripheral.
Related: Android BLE Connection Problems: 7 Mistakes and Fixes.