Service keeps getting destroyed

守給你的承諾、 提交于 2019-12-04 19:56:26

The problem is the bind/unbind in onCreate/onDestroy. I can't really explain it, but binding in that lifecycle states leads to getting the service destroyed even though you use startService() in onCreate() of the activity.

This setup now works nicely:

  • In activity's onCreate() use startService() to get the service started.
  • The onStartCommand() of the service has to return Service.START_STICKY
  • In Activity's onResume() bind to the service
  • In Activity's onPause() if something is playing, call startForeground() of the service and unbind from it.
  • In Activity's onDestroy() call stopService() if nothing is currently playing.

Here's your answer.

A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

You should call startService() instead.

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