Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 786
Willie Chalmers III Avatar asked Aug 05 '17 18:08

Willie Chalmers III


2 Answers

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.

like image 179
Alexander Abakumov Avatar answered Nov 15 '22 06:11

Alexander Abakumov


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.

like image 26
Oleg Gryb Avatar answered Nov 15 '22 04:11

Oleg Gryb