I read in the docs that Context.startForegroundService()
has an implicit promise that the started service will call startForeground()
. However, since Android O is coming out with changes to background and foreground services, are there any other performance improvements that it has compared to using the older startService()
method, or is it just best practice going forward?
It's about neither performance improvements, nor benefits, nor best practice.
Starting from API 26, system just doesn't allow a background app to create a background service.
So, if your app is in the background (you're welcome to do the same if it's in the foreground as well), you have to to use Context.startForegroundService(Intent)
instead of the former startService(Intent)
. The service must then call startForeground(int, Notification)
within first 5 seconds after it has started, otherwise system will stop the service.
It should also be mentioned that there is information that the old way with starting a service with startService(Intent)
from a background app still works on the current release of Android Oreo, but it will be fixed soon.
Hence, starting from the API 26, you want to use new Context.startForegroundService(Intent)
method instead of startService(Intent)
whenever you want to start a foreground service.
As I've explained here, startForegroundService has a serious problem that will inevitably lead to infrequent ANR's. Since this problem can't be fixed at an app level, startForegroundService should not be used. I switched to JobScheduler and JobService model to implement the same functionality.
The latter model works well so far and I didn't see app crashes in Play Store anymore. The new model is quite different though and I've spent two days re-factoring existing code based on startForegroundService, but it has definitely paid off.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With