问题
I have a device that is a simple BLE device with a button, and I need to detect when the user long presses the device (via characteristic change) even when the app is in the background.
This click will trigger a remote call the server.
I have two questions regarding this:
#1 Can I have this achieved without a foreground service?
#2 If I have a foreground service running with the BLE GATT callbacks how can I detect when the device is in range again?
My current solution is to have a foreground service always running in the background but with that, the user will need an always showing notification of the app.
回答1:
1: Yes you can achieve this without using a foreground service, by using a JobIntentService.
This type of service does not require to display a notification to your user.
To know when the device button has been clicked, your JobIntentService could scan for BLE devices, and you could include in the BLE data advertised by your device a flag or timestamp of the last click.
In order to avoid draining the battery, I suggest you don't scan continuously, but only for a few seconds every minute.
2: If your BLE scanner receives BLE data advertised by the device, it means the device is within range.
来源:https://stackoverflow.com/questions/57464126/how-to-detect-bluetooth-changes-connection-state-and-characteristic-when-app-i