Search code examples
androidibeaconibeacon-android

Android Beacon Library - Manually starting background scan


This is a question regarding Android Beacon Library.


Because of Android 8 (Oreo)'s restriction on background service, the author of the library has changed the mechanism of starting background service in Android 8.

As far as I can observe, the background service needs a much longer time to start than Android 7 or below, even if the app is already started.

What I want to do is to reduce this time as much as possible.
One of the way is to force launch the background scanning if the app is opened by the user.
For instance, I want to do something like

BeaconManager.getInstanceForApplication(this).startbackgroundScanningIfNotRunning();

In onCreate() of MainActivity.

But I think there is no such API. Is there anyway to do this?

Or, is it possible for the library to handle itself (through an app update)?


Solution

  • While it is possible to do something like described in the question, it may not be useful. The problem is that Android 8 prevents apps from running in the background long-term. In order to manually start a scan in the background, your app must be running in the first place. If Android 8 has disallowed this, then you aren't going to be able to do it, anyway.

    For an explanation of how Android 8 blocks apps from running in the background and how the library works around this, you can read this blog post if you have not already: http://www.davidgyoungtech.com/2017/08/07/beacon-detection-with-android-8

    If you have somehow managed to get your app running long-term in the background (e.g. by using a foreground service), you can always kick off a scan manually by starting beacon ranging/monitoring in foreground mode (from the library perspective), which will schedule an immediate ScanJob that will keep running and start itself over and over. To make sure you are in foreground mode, you simply need to refrain from using the BackgroundPowerSaver and don't make any calls to beaconManager.setBackgroundMode(...) to true.