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

FBI Warning:欢迎转载,但请标明出处:,未经本人同意请勿用于商业用途,感谢支持!

项目开发中有遇到startService与bindService混合使用的情况,发现其对Service生命周期有很大影响,故与各位分享一下。。。

一、正常情况(应该大家都很熟了,简单介绍):

(1)单独使用startService():

onCreate()->onStartCommand()->Servicerunning->onDestroy()->Serviceshutdown

(2)单独使用bindService():

onCreate()->onBind()->Clientsareboundtoservice->onUnbind()->onDestroy()->Serviceshutdown

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

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

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

(2)bindService:调用onBind()

(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?我们来看官方的解释:

NotethatifastoppedservicestillhasServiceConnectionobjectsboundtoitwiththeBIND_AUTO_CREATEset,itwillnotbedestroyeduntilallofthesebindingsareremoved.

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

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

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

Whenthelastclientunbindsfromtheservice,thesystemdestroystheservice(unlesstheservicewasalsostartedbystartService()).

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

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

详细的解析各位可参考官方API文档:

获致幸福的不二法门是珍视你所拥有的遗忘你所没有的。

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

相关文章:

你感兴趣的文章:

标签云: