AltBeacon / android-beacon-library

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

Update foreground service support for Android 14 restrictions #1155

Closed davidgyoung closed 9 months ago

davidgyoung commented 10 months ago

This updates the library to support the upcoming Android 14 release, which imposes new restrictions on starting a foreground service.

This adds the necessary AndroidManifest.xml declarations for foreground services on Android 14, and also checks that Manifest.permission.ACCESS_FINE_LOCATION has been granted by the user in the call to beaconManager.enableForegroundServiceScanning(...). If permission is not obtained when this call is made, the method now throws a SecurityException to let the user know this is a requirement.

I have tested this on a Pixel 7 running Android 14 Beta 5 using a special branch of the Kotlin reference app and confirmed that the SecurityException crashes the app as described above before permission is granted, and it works to detect beacons with the Foreground service if the call is made after permission is granted.

It is unfortunate that this solution crashes the app rather than gracefully recover. But at least the SecurityException happens during a library call, with a helpful message about what the developer needs to do, vs. during the OS startup of the service with a less helpful message.

A more graceful recovery would mean one of two things:

  1. Don't crash the app, but leave beacon scanning broken. (I like this solution even less, as it will hide the problem for many developers.)
  2. Avoid a crash by not starting the foreground service if permission is not granted, then listen for the permission being granted, and if it is granted, start the foreground service at that time.

The problem with option 2 is that it is very complicated -- it is not easy to listen for this permission being granted. And then the library gets in the business of managing permissions, something it does not do now. Any alternative thoughts appreciated.

davidgyoung commented 10 months ago

2.20-beta1 release has this change and the kotlin reference app has been updated to use the beta version of the library and change the permissions flow for foreground services here