星期一, 4月 30, 2012

return values of Android Service onStartCommand

實做 Service 時,最重要的應該就是 onStartCommand 的實作了吧,當其他 context 呼叫 startService 時,這個函數都會被呼叫。
onStartCommand 的回傳值可以有 4 種,分別是 START_NOT_STICKYSTART_REDELIVER_INTENTSTART_STICKY 跟 START_STICKY_COMPATIBILITY

若回傳 START_NOT_STICKY,表示這個服務不需要一直存留,當 Service 因其他程序需要記憶體砍掉以後,除非有另一次的 startService 呼叫,不然系統不會幫你重新執行 Service。

回傳 START_REDELIVER_INTENT 時,若 Service 被砍掉以後,系統會嘗試使用當初呼叫 startService 的 intent 來重新啟動這個 Service。

START_STICKY 跟 START_REDELIVER_INTENT 類似,但並不會保留上次用來開啟服務的 intent,也就是說如果 service 被系統砍掉後重開,被砍掉到重新啟動中間如果沒有 startService 來傳遞新的 intent,送進來的 intent 就有可能為 null,所以如果在 onStartCommand 裡面需要讀取 intent 裡的 bundle 一定要先確認 intent 是否為 null。

最後一個 START_STICKY_COMPATIBILITY,跟 START_STICKY 一樣,但根據官方的文件,使用這個 return code 時當 service 被砍掉後系統不一定會再呼叫一次 onStartCommand。也就是說如果是 sticky 的話系統一定會再 reschedule 一個 onStartCommand 嗎.?

Refs:
http://developer.android.com/reference/android/app/Service.html

沒有留言: