Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android IntentService 淺談與原始碼分析

編輯:關於 Android 程式設計

啟動 Service 時,它預設運行在主執行緒。若 Service 執行非常耗時或可能被阻塞的操作,應用程式會被掛起,甚至出現 ANR 錯誤。為避免此問題,應在 Service 中重新啟動一個執行緒。但有個更好的方法——使用 IntentService。

IntentService 的優勢

IntentService 以佇列方式將請求的 Intent 加入佇列,再開啟一個工作執行緒來處理。對於非同步的 startService 請求,它會處理完一個再處理下一個,每個請求都在獨立的工作執行緒中處理,不會阻塞主執行緒。因此,若有耗時操作,與其在 Service 裡手動開啟執行緒,不如直接用 IntentService 來處理。

對比範例

普通 Service 若在 onStart 中直接 Thread.sleep,會阻塞主界面並出現 Application not responding:

public void onStart(Intent intent, int startId) {
  // Service 裡不能進行耗時操作,必須手動開啟工作執行緒
  try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); }
}

而 IntentService 則可以在 onHandleIntent 中安全地進行耗時操作:

public class MyIntentService extends IntentService {
  public MyIntentService() { super("m"); }
  @Override
  protected void onHandleIntent(Intent intent) {
    // IntentService 裡面是可以進行耗時操作的
    try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); }
  }
}

連續兩次啟動 IntentService 時,應用程式不會阻塞,第二次請求會在第一次結束後才運行。

原始碼分析

IntentService 內部有一個 ServiceHandler(繼承 Handler),也有服務與訊息循環的功能。在 onCreate 中,它會建立並啟動一個 HandlerThread,取得 Looper 後初始化 mServiceLooper 與 mServiceHandler:

public void onCreate() {
  super.onCreate();
  HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
  thread.start();
  mServiceLooper = thread.getLooper();
  mServiceHandler = new ServiceHandler(mServiceLooper);
}

在 onStart 中,會產生一條附帶 startId 與 Intent 的 Message 並送進 MessageQueue:

public void onStart(Intent intent, int startId) {
  Message msg = mServiceHandler.obtainMessage();
  msg.arg1 = startId;
  msg.obj = intent;
  mServiceHandler.sendMessage(msg);
}

當 Looper 發現 MessageQueue 中有訊息,就會呼叫 handleMessage,在其中執行 onHandleIntent 處理工作,完成後以 stopSelf(msg.arg1) 結束指定工作:

public void handleMessage(Message msg) {
  onHandleIntent((Intent) msg.obj);
  stopSelf(msg.arg1);
}

所有工作執行完後會呼叫 onDestroy,將 Looper 的 quit:

public void onDestroy() { mServiceLooper.quit(); }

由此可見,IntentService 是一個基於訊息的服務。每次啟動時並非立即處理,而是先建立 Looper 與 Handler,並在 MessageQueue 中加入附帶 Intent 的 Message;當 Looper 發現訊息後,再取出 Intent 在 onHandleIntent 中呼叫你的處理邏輯,處理完後即停止服務,接著處理下一個訊息。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved