Closed davidgyoung closed 11 months ago
@stephenruda can you please take look at this change and let me know your thoughts? I know you said your app already starts up the foreground service outside Application.onCreate so this is not an issue for you. But I would like your thoughts on the general approach. It would also be good to confirm this won't cause any trouble for your app.
Once I can get this merged I will roll a new library release with your change and this change.
@davidgyoung
I think this is a nice solution.
My application has battery optimizations disabled, which is an additional exemption for starting a foreground service from the background. So for me it didn't matter if I started the service in the Application.onCreate()
before the BOOT_COMPLETE
event because I was already exempt.
I did test your branch in my app under all conditions I could think of...
Everything is working exactly as expected. If I don't have battery optimizations disabled (so getting rid of my additional exemption), I see the exact same logs as you. It fails to start the service in the onCreate()
and it successfully retries after the BOOT_COMPLETE
event.
I think this does a good job of solving the problem and I don't see any issues - so I would say it is good to go!
Android 14 introduced a change that restricts foreground service starts after BOOT_COMPLETED to only be allowed after the broadcast receiver event for BOOT_COMPLETED fires for the app.
Because of this, any app that tries to start beacon scanning with a foreground service enabled from
Application.onCreate
will fail, and the library will detect this and fall back to using the Job Scheduler. This did not happen on Android 12/13. As of those OS versions, starting up a foreground service after boot fromApplication.onCreate
worked fine.This change makes it so that the library will check for the previous failure to start the foreground service when handling the BOOT_COMPLETED event, and retry starting up the foreground service at that time.
I tested this on a Pixel 7 / Android 14 with the Kotlin reference app configured to use a foreground service. I rebooted the phone and captured the LogCat output, and visually confirmed the foreground service notification was displayed.
As you can see from the log below, the initial attempt to start the foreground service fails,
11:24:35.861 17785 17785 W BeaconManager: Foreground service blocked by ServiceStartNotAllowedException. Falling back to job scheduler
and the retry from the BroadcastReceiver succeeds.11:24:36.006 17785 17785 I BeaconManager: successfully started foreground beacon scanning service.