天天看點

我的Android進階之旅------>Android服務的生命周期回調方法

            先引用一段官網上的文字

==================================================================================================

called. Note that multiple calls to Context.startService() do not nest (though they do result in multiple corresponding calls to onStartCommand()), so no matter how many times it is started a service will be stopped once Context.stopService() or stopSelf()

to ensure the service is not stopped until started intents have been processed.

used for services that should only remain running while processing any commands sent to them. See the linked documentation for more detail on the semantics.

allowing the client to then make calls back to the service. The service will remain running as long as the connection is established (whether or not the client retains a reference on the service's IBinder). Usually the IBinder returned is for a complex interface

is called and the service is effectively terminated. All cleanup (stopping threads, unregistering receivers) should be complete upon returning from onDestroy().

當采用Context.startService()方法啟動服務,與之有關的生命周期方法

onCreate()-->onStart()-->onDestory()

onCreate()方法在服務被建立是調用,該方法隻會被調用一次,無論調用多少次startService()

或者bindService()方法,服務也隻被建立一次。

onStart()方法隻有采用Context.startService()方法啟動服務時才會回調該方法。該方法在服務開始運作時被調用。多次調用startService()方法盡管不會多次建立服務,但是onStart()方法會被多次調用。

onDestory()方法在服務被終止時調用。

當采用Context.bindService()方法啟動服務,與之有關的生命周期方法

onCreate()-->onBind()-->onUnbind()-->onDestory()

onBind()方法隻有采用Context.bindService()啟動服務時才會回調該方法。該方法在調用者和服務綁定時被調用,當調用者和服務已經綁定,多次調用Context.bindService()方法并不會導緻該方法多次被調用。

onUnbind()方法隻有采用Context.bindService()啟動服務時才會回調該方法。該方法在調用者和服務解除綁定時被調用。

如果先采用Context.startService()方法啟動服務,然後調用Context.bindService()方法綁定到服務,再調用Context.unbindService()方法解除綁定,最後調用Context.bindService()方法再次綁定到服務,觸發的生命周期方法如下:

onCreate()-->onStart()-->onBind()-->onUnbind()[重載後的方法需傳回true]-->onRebind()

  作者:歐陽鵬  歡迎轉載,與人分享是進步的源泉!

繼續閱讀