How to detect bluetooth changes (connection state and characteristic) when app is in background without a foreground service

送分小仙女□ 提交于 2021-01-29 13:10:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!