0

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.

Bruno Oliveira
  • 255
  • 1
  • 8
  • 1
    At least on newer Android versions, the user can go into system settings, find the app and disable the Foreground Service notification if it's annoying. – Emil Aug 12 '19 at 22:12

1 Answers1

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.

matdev
  • 4,115
  • 6
  • 35
  • 56
  • I would avoid JobIntentService for this kind of task. One reason is because it holds a wake lock which prevents the CPU to go to sleep (compared to when you run a Foreground service instead, where the Bluetooth chip will wake up the CPU when something happens). Also it seems you can only run a JobIntentService for 10 minutes (https://stackoverflow.com/questions/49254700/what-is-the-maximum-job-execution-time-of-onhandlework-of-jobintentservice). – Emil Aug 12 '19 at 22:10
  • I'm not recommending using JobIntentService for this kind of task, just answering the question for an alternative to using a foreground service. Also, if the JobIntentService is used sparingly, say for no longer than 5 or 10 seconds every 1 or 2 minutes, I think it can do the job. – matdev Aug 13 '19 at 07:40