Service
Service生命週期
Service啓動方式
- 第一種形式:通過startService()啓動Service:
- 如果Service沒被創建先執行onCreate(),再執行onStart()方法,Service開始運行。
- 如果Service已經存在,則只調用onStart()方法。
- 只有調用stopService()方法才能關閉Service。如果調用者退出但是沒有調用stopService()方法,Service依然在後臺運行。
- 第二種形式:通過bindService()方法啓動Service:
- 調用bindServcie()後,如果Service沒被創建會先執行onCreate,然後執行onBind()方法,並返回IBinder接口實例,允許其調用Service的方法。
- 使用bindService()方法啓用服務,調用者與服務綁定在了一起,調用者一旦退出,系統會調用onUnbind()和onDestroy()方法,服務就會終止。
- Service只能被綁定一次,如果另一個調用者希望綁定,可以先讓前者unbindService()解除綁定。當然,在unbindService()執行之後,系統會調用Service的onUnbind()和onDestroy()方法終止服務。
Service與Activity通信
- 通過綁定之後的binder。
- 通過broadcastReceiver(廣播接受者)。
- AIDL
IntentService
IntentService代碼包含了一個工作線程Thread、工作線程的Looper、工作線程的Handler。
在onCreate()方法中創建了子線程HandlerThread,然後利用HandlerThread提供的Looper創建消息循環。
在onStart()方法中將Intent作爲消息發送給Handler,最終交由onHandleIntent方法處理.
在destroy()方法會銷燬消息循環,進而子線程終止.