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

天涯浪子 提交于 2020-02-20 06:44:27

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/45525214/are-there-any-benefits-to-using-context-startforegroundserviceintent-instead-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!