Are there any benefits to using Context.startForegroundService(Intent) instead of Context.startService(Intent) for foreground services?

Willie Chalmers III :

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?

Alexander Abakumov :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=433162&siteId=1