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

Android 官方訓練課程:IntentService 的工作請求送出與處理

編輯:關於 Android 程式設計

原文翻譯整理自 Android 官方訓練課程「傳送請求到背景服務」。上一節我們學會了如何建立 IntentService,這一節則要學習如何透過 Intent 讓 IntentService 执行工作請求。

Intent 可以把任何資料交給 IntentService 處理,你可以在 Activity 或 Fragment 的任意方法中送出 Intent 給 IntentService。

建立並送出工作請求

要建立一個工作請求並送給 IntentService,首先需要建立一個顯式的 Intent 物件,向其加入請求資料,最後透過 startService() 送達。

第一步,為名為 RSSPullService 的 IntentService 建立一個顯式 Intent,並把 URI 放進 Intent 的 data 欄位:

/*
 * Creates a new Intent to start the RSSPullService
 * IntentService. Passes a URI in the
 * Intent's "data" field.
 */
mServiceIntent = new Intent(getActivity(), RSSPullService.class);
mServiceIntent.setData(Uri.parse(dataUrl));

第二步,呼叫 startService():

// Starts the IntentService
getActivity().startService(mServiceIntent);

要注意的是,你可以在 Activity 或 Fragment 的任何地方送出工作請求。舉例來說,如果你需要先取得使用者的輸入資料,就可以把送出請求的程式碼放在按鈕的點擊回呼裡。

一旦呼叫了 startService(),IntentService 便會在 onHandleIntent() 方法中執行工作請求,並在任務完成後自動停止。這正是 IntentService 的便利之處——它為你打理好背景執行緒與生命週期,不必手動管理。

下一個步驟,是如何把工作完成的結果回饋給請求的來源。這可以透過 BroadcastReceiver 來達成,也就是官方課程的下一節內容。

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