1. 程式人生 > >Service和IntentService 區別和使用

Service和IntentService 區別和使用

背景

最近開發遇到一個小小的問題,因為沒怎麼用過IntentService ,所以對其生命週期也不很瞭解,還有工作原理。


intentService 詳解

  1. intentService ——>> StartService 第一次
    這裡寫圖片描述

  2. intentService ——>> BindService 第一次
    這裡寫圖片描述

  3. intentService ——>> StartService 多次
    這裡寫圖片描述

  4. intentService ——>> BindService 多次

    無任何生命週期回撥
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

當我們通過startService多次啟動了IntentService,這會產生多個job,由於IntentService只持有一個工作執行緒,所以每次onHandleIntent只能處理一個job。多個job,IntentService會如何處理?處理方式是one-by-one,也就是一個一個按照先後順序處理,先將intent1傳入onHandleIntent,讓其完成job1,然後將intent2傳入onHandleIntent,讓其完成job2…這樣直至所有job完成,所以我們IntentService不能並行的執行多個job,只能一個一個的按照先後順序完成,當所有job完成的時候IntentService就銷燬了,會執行onDestroy回撥方法

總結:
onHandlerIntent 其實是相當於一次 Thread 進行一次Run。 可以通過多次啟動多次開啟IntentService 來執行。

方法:
1.外部多次while,startService ———– 意味著同時開啟多次Thread
2.內部在onHandlerIntent 內部 資料處理結束後,就在一次StartService 重新啟動 ——————–意味著一次執行緒結束在開啟一次執行緒 (串)
3.也可以在內部while(flag)
—————意味這在一個執行緒內處理跟多的操作


Service 詳解

  1. Service ——>> StartService 第一次
    這裡寫圖片描述
  2. Service ——>> BindService 第一次
    這裡寫圖片描述
  3. Service ——>> StartService 多次
    這裡寫圖片描述
  4. Service ——>> BindService 多次

本章完