標籤:
@、Context.startService(Intent)
lifecycle callback:
1、onCreate(...)
2、onStartCommande(Intent, int, int)
3、onDestroy()
stop service:
1、Service.stopSelf() / stopSelf(int)
2、Context.stopService(Intent)
@、Context.bindService
lifecycle callback:
1、onBind(...)
2、onUnbind()
stop service:
1、Context.unbindService() (當所有用戶端都執行完此操作,服務會自動關閉,除了調用Service.startForeground()的情況。)
@、保持Service不被終止
在服務裡調用startForeground(),這種情況要正確調用stopForeground()來終止服務,否則服務一直運行。
@、與Activity通訊:
1、使用sendBroadcast(Intent)。
2、在Service中添加會調介面及介面執行個體及執行個體的set方法,而Activity實現此介面。這種方法可結合Locally Bound Service模式進行使用,這樣可以在Activity中直接調用Service的方法。
@、IntentService
1、HandlerThread,Handler,Message模式。
2、繼承IntentService只需要實現onHandleIntent(Intent)方法。
3、以上兩點決定了,使用IntentService不用再建立線程,而onHandleIntent每次只能處理一個Intent,因此如果存在耗時間長度的Intent,則此IntentService的其他Intent就有可能被阻塞。
@、自訂Service實現並行服務
1、在自訂Service中添加ExecutorService執行個體成員,通過它的excute(Runnable)來執行任務。通過startForeground(),保持服務後台運行,通過計數成員變數記錄當前任務數量,根據當前任務數量決定是否調用stopForeground()來終止服務。
註:關於Service的樣本見Android Programming: Pushing the Limits -- Chapter 6: Services and Background Tasks。
Android -- Service