serviceibeaconaltbeaconibeacon-androidandroid-ibeacon

How to enable altbeacon android library forground service only if entered beacon region?


I'm using altbeacon android library for beacon detection in my app. It runs foreground services as a feature by default, but I only want to run foreground services when I enter a beacon region or when one beacon is detected. This problem does not appear to be documented anywhere. Would you be able to help me?


Solution

  • Using AndroidBeaconLibrary 2.19+, autobind APIs can be used to easily switch to using a foreground service after a detection.

    The basic steps are:

    1. In a custom Application class, call beaconManager.startMonitoring(region) in the onCreate() method. This sets up initial beacon detections using scheduled jobs.

    2. When you get a callback to didEnterRegion() you will need to call beaconManager.stopMonitoring(...) and beaconManager.stopRanging(...) for all monitored and ranged regions.

    3. After step 2, configure the library for a foreground service as shown here

    4. Again start monitoring/ranging any desired regions.

    Be careful with the above approach, as standard Android will block starting a foreground service from the background in Android 12 in some cases. In addition, some non-standard OEMs already do this on earlier Android versions.

    In general, the recommended practice is to set up the foreground service only if (a) the app is in the foreground or (b) you know the user has recently interacted with your app's UI. If Android blocks your app from starting the foreground service, starting monitoring/ranging from the background with a foreground service configured will cause your app to crash. Because the conditions that may cause this are complex and hard to predict, this technique may lead to unexpected crashes and related bugs.

    One alternative to the above is to use the new IntentScanStrategy introduced in the library, which allows faster background scanning without the need for a foreground service.