Scanner in foreground service, Android

My company is developing an app using the Estimote technology and we need to start scanning for beacons in background upon the system boot using a ProximityObserver created in a BroadcastReceiver in its onReceive(…) method using the withScannerInForegroundService(…) option.

This approach works well, however, we need to have an option to turn off the monitoring of beacons in the application. Normally, that would be done using the ProximityObserver.Handler calling its stop() method, however, in our case we have no way of holding the reference to this object as it is created in the BroadcastReceiver where the observation is started.

Is there any other way of how to turn the scanner off or the only way is to keep a reference to the ProximityObserver.Handler?

Thank you for your help.

Hey @Milan

When your BroadcastReceiver reacts on the BOOT broadcast, it runs in your App process. Having that in mind, the one possible solution is to hold a reference to the current scan inside a singleton class with a static access. Then you will be able to call it from any other app component, like activity, and stop it when necessary.

Second idea is to write your own foreground service implementation, that will not use . withScannerInForegroundService when declaring ProximityObserver. In such way you could possibly launch FG service through the BroadcastReceiver and stop it later on through any activity (by binding it to that service), plus write some custom logic to remotely stop scanning (call handler’s .stop()). Btw. watch out for launching non-foreground services from BroadcastReceiver - AFAIR it is forbidden since Android 8.0. This is why we are encouraging people to use foreground service to do the scanning.

Both solutions will need you to write some custom logic, but it’s possible to achieve the expected behaviour :slight_smile:

Kind regards,
Paweł

Hi Paweł,
thank you for your answer I believe the second idea will help us achieve what we need.

Best regards,
Milan

1 Like

Hi, I am working on an app that uses withScannerInForegroundService and need an option to stop scanning from notification itself(without having to open the app). I am checking to see if there are any option available now to remotely stop scanning. Also, given that non foreground services cannot be started from broadcast receiver since Android 8, what are the alternate available solutions?

Thanks in advance.