FBI Warning:歡迎轉載,但請標明出處:http://blog.csdn.net/codezjx/article/details/45314925,未經本人同意請勿用於商業用途,感謝支持!
項目開發中有遇到startService與bindService混合使用的情況,發現其對Service生命週期有很大影響,故與各位分享一下。。。
一、正常情況(應該大家都很熟了,簡單介紹):
(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