This guide is for Android only, as iOS unforunately doesn't allow for backgrounded BLE communication.
Android allows us to scan for and communicate with BLE peripherals while our app is in the background. There are two ways of going about it, mostly dictated by Android background limitations first introduced in Android O.
AbleLib takes care of all of that, and allows you to readily deploy background BLE processes with minimal effort. In its basic implementation, the
You can only run a single BLE service at the time, as deploying more than one wouldn't make sense.
Start off by calling
AbleManager#setUpService to set all relevant parameters:
AbleManager.setUpService( serviceClass = AbleService::class.java, notification = AbleService.defaultNotification(context, "My App", "Hey, running!", R.drawable.icon, MyMainActivity::class.java), backgroundScanOutsideApp = true, backgroundScanInApp = true )
The parameters are as follows:
Serviceclass that contains your scanning logic. It must be
AbleServiceor its subclass. Check out this section for more info.
Notificationthat'll be shown to the user when the service is ran in the foreground. You can provide a notification of your own, or make use of
AbleService#defaultNotification, which will construct a notification with the provided title, message and icon, and will open the provided
backgroundScanOutsideApp- if the service should scan when the app is backgrounded.
backgroundScanInApp- if the service should scan when the app is foregrounded.
After your service is set up, you can start it with
AbleManager#refreshBackgroundServiceState, which will be your go-to point for whenever you make changes with
AbleManager will automatically detect your app state and start/stop the service in the appropriate mode, foreground or background, depending on
AbleManager.refreshBackgroundServiceState() // call this whenever you need to (re)start/stop your service
You can manually stop and remove the service with
In its default implementation,
AbleService lives in the background and scans for nearby paired peripherals. Once it finds any, it sends a broadcast with
action = AbleService.ACTION_DEVICE_FOUND, and the found
AbleDevice packed as a
Parcelable extra with key
AbleService class is open and can be subclassed in order to implement any behaviour that you'd like. The best way of going about it is just to override open methods
onStop, which, in the default version, contain the logic for starting and stopping the scanning process. Then, make sure to pass your subclass's class in