startService与bindService混合使用对Service生命周期的影响

来源:互联网 发布:摄像慢镜头软件 编辑:程序博客网 时间:2024/05/06 00:03

一、正常情况

(1)单独使用startService():

onCreate()->onStartCommand()->Service running->onDestroy()->Service shut down

(2)单独使用bindService():

onCreate()->onBind()->Clients are bound to service->onUnbind()->onDestroy()->Service shut down

 

二、共同使用情况(startService->bindService  或者 bindService  ->startService,顺序无所谓):

例子一:按顺序1,2,3,4执行

(1)startServic:调用onCreate()->onStartCommand()

(2)bindService:调用onBind()

(3)stopService:没有调用onDestory()    Service仍然在运行!

(4)unbindService:调用onUnbind()->onDestory()    此时Service关闭!

 

例子二:将例子一3,4调换

(1)startServic:调用onCreate()->onStartCommand()

(2)bindService:调用onBind()

(3)unbindService:调用onUnbind()    Service仍然在运行!

(4)stopService:调用onDestory()     此时Service才关闭!

 

从上面的微妙变化,我们可以得出一个结论:停止服务销毁服务是两个不同的概念,虽然我们调用了stopService去停止服务,但是服务仍然木有销毁,依然坚挺的运行着。直至我们调用了onUnbind,与Service关联的client都解绑以后,Android系统才调用onDestroy将其销毁。

Why?我们来看官方的解释:

Note that if a stopped service still has ServiceConnection objects bound to it with the BIND_AUTO_CREATE set, it will not be destroyed until all of these bindings are removed.

总结:若被停止的服务依然有ServiceConnection 与其绑定,则服务不能销毁,直至我们把所有ServiceConnection 解绑

 

相应的,例子二当我们使用onUnbind去解绑后,服务依然运行,直至用户调用stopService,Service才可销毁。

Why?我们来看官方的解释:

When the last client unbinds from the service, the system destroys the service (unless the service was also started by startService()).

总结:当所有ServiceConnection 解绑后,系统会自动销毁服务。注意括号里面的内容:不包括同时用startService()启动的情况。此时,我们不得不再调用一次stopService来销毁它



给大家分享官方的一张图,更直观一些:




详细的解析各位可参考官方API文档:http://developer.android.com/guide/components/bound-services.html

阅读全文
0 0