1. 程式人生 > >Service的兩種啟動方式和區別?

Service的兩種啟動方式和區別?

第一種啟動方式:startService(Intent)啟動服務 生命週期方法流程:onCreate --- > onStartCommand 關閉服務:stopService(Intent)關閉服務 生命週期方法流程 :onDestory第二種啟動方式:bindService(Intent , ServiceConnection , flag)啟動服務 生命週期方法流程:onCreate --- > onBind關閉服務:stopService(Intent)關閉服務 生命週期方法流程 :onUnBind ----> onDestory區別:startService啟動Service ,Service有獨立的生命週期,不依賴該組建;
多次呼叫startService方法,會重複呼叫onStartCommand方法;必須通過stopService或者stopSelf來停止服務(IntentService會自動呼叫stopSelf方法)bindService啟動Service,多次呼叫此方法,只會呼叫一次onBind方法;bindService,Service 依賴於此元件,該元件銷燬後,Service也會隨之銷燬。擴充套件:1,同一個Service,先啟動startService,然後在bindService,如何把服務停掉?    無論被startService呼叫多少次,如需要stopService或者stopSelf方法 一次;
    呼叫n次bindService,必須呼叫n次unBindService方法;因此,需要呼叫一次stopService(或者stopSelf)方法,和n次unBindService方法,執行順序沒有要求,最後一個stopService或者unBindService方法會導致Service的 onDestory執行。2,Service的生命方法是執行在那個執行緒中?Service預設執行在主執行緒,所以其生命方法也是執行在主執行緒中,如果需要在Service中進行耗時操作,必須另起執行緒(或者使用IntentService)否則會引起ANR。