George Edwards
George Edwards

Reputation: 9229

Running BLE in background on Android

Where I'm Currently At:

I would like to be able to run Bluetooth in my app in the background on android. I have read various guides and understand the idea of creating an intent service (something like android.app.IntentService and extending it, overwriting the onHandleIntent with your desired behaviour) however, I don't understand how that would interract with my existing behaviour? So for example, I currently call:

...
var bluetoothManager = utils.ad.getApplicationContext().getSystemService(android.content.Context.BLUETOOTH_SERVICE);
adapter = bluetoothManager.getAdapter();
adapter.startLeScan(Bluetooth._scanCallback)
...

(this is in JavaScript, using the nativescript runtime, so don't worry about it looking a bit wierd.)

Where I'm trying to get to:

I would like to being able to scan for and reconnect to paired devices in the background and recieve (store in SQLite) GATT Characteristic updates.

Question:

So how do I create this functionality in the type of service that can be run in the background as described above?

Upvotes: 1

Views: 4905

Answers (1)

Emil
Emil

Reputation: 18472

The Bluetooth LE Gatt APIs are built upon Android's Binder mechanism, which means it will only work during the app process is alive. You must make sure your app process isn't killed by the system. The easiest way to do that is to have a foreground service running (not an intent service). The only important thing is that the foreground service is alive and running, your service class itself doesn't have to do anything. But I guess the easiest way is to put all your BLE code inside that service. See https://developer.android.com/guide/components/services.html#Foreground.

Upvotes: 5

Related Questions