AltBeacon / android-beacon-library

Allows Android apps to interact with BLE beacons
Apache License 2.0
2.84k stars 836 forks source link

Background beacon scanning without a foreground service #1030

Closed davidgyoung closed 3 years ago

davidgyoung commented 3 years ago

This is an experimental implementation of background scanning without a foreground service.

Generally on Android it is not possible to do regular BLE scanning without a long running service to host the timers. And on Android 8+ this must be a foreground service.

However, Android 8+ does offer an alternative appropriate for some use cases. You can do a constant BLE scan with matching results delivered by an Android Intent. This will wake up a suspended app as needed to deliver the results. There are, however, some limitations:

  1. Beacon Ranging results cannot be delivered at regular intervals if bluetooth devices are not detected. If no devices are detected, ranging callbacks will simply stop.
  2. Similarly to the above, Beacon monitoring exit region results cannot be delivered quickly. It might take 25 minutes for a scheduled job to deliver a region exit.
  3. For apps expected to run with large quantities of beacons in the vicinity or ones that transmit at a high rate (10 Hz or more), this can be draining of phone battery when beacons are around.

This technique effectively trades fast "loss of detection" times for not having a foreground service. If an app can live with this tradeoff, this technique may be beneficial.

To use it, simply set this in config:

beaconManager.setIntentScanningStrategyEnabled(true);

Completed tasks: [x ] Set up a Scheduled Job to deliver region exit events and empty ranging events every ~15 minutes. [x] Set up scan filters matching on the whole identifier to prevent excessive battery use when beacons of non-interest are around. [x ] Build a way to detect if the scan filters used in this technique don't work on a specific device model and offer the option of automatically turning it off in these cases. (Perhaps this can be done with a scheduled job that does a brief scan to look for beacons -- if the beacons are seen in the job but not in the intent-backed scans this would indicate that the technique fails.

Battery drain still remains to be tested

davidgyoung commented 3 years ago

This is available in 2.19-beta2