startService和bindService最好不要混用

时间:2022-09-13 16:52:54


startService和bindService最好不要混用,当然,如果你对Servie的生命周期烂熟于心的话,你想怎么用就怎么用。

个人建议还是不要混用,以免思维混乱,吧自己搞的云里雾里的。


使用startService启动的Service,在调用方销毁后,Service任然运行,除非调用自己调用stopSelf或者外部调用stopService()

主要,如果某个app中Service没有销毁的话,这个app也不会销毁,常驻内存。


官方文档说的最好: http://developer.android.com/guide/components/services.html



Started A service is "started" when an application component (such as an activity) starts it by calling  startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself. Bound A service is "bound" when an application component binds to it by calling  bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). 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.
These two paths are not entirely separate. That is, you can bind to a service that was already started with startService() . For example, a background music service could be started by calling  startService()  with an Intent  that identifies the music to play. Later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling  bindService() . In cases like this,  stopService()  or  stopSelf()  does not actually stop the service until all clients unbind.  
两种启动方式可以混用,Activity可以bind到一个已经使用startService()启动过的service,用来执行一些对service的控制,或者从service获取一些信息。在这种情况下,stopService()或者stopSelf()并不能停止server,直到所以的客户端调用unbind。反之,所以的客户端unbund后,也不能停止service,必须调用 stopService()或者stopSelf()