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

Android Started Service 實戰:IntentService 與 Service 的選擇

編輯:關於 Android 程式設計

什麼是 Started Service

當應用元件呼叫 startService 時,系統會建立或啟動一個服務,並透過 Intent 傳入參數。服務可在 onStartCommand 中取得這些參數,並在背景執行工作。

兩種實作方式

1. 擴充 Service

Service 是所有服務的基礎類別。由於服務預設執行在主執行緒,若直接進行耗時工作,會拖慢 UI。因此通常需要在 Service 中建立獨立工作執行緒,例如使用 HandlerThread。

2. 擴充 IntentService

IntentService 是 Service 的子類別,會建立工作執行緒與佇列,逐一處理啟動請求。所有 Intent 都會交給 onHandleIntent 處理,完成後服務會自動停止,適合不需要同時處理多個請求的情境。

onStartCommand 的回傳值

當系統因資源不足而結束服務時,onStartCommand 的回傳值會決定後續行為。START_NOT_STICKY 表示服務不會自動重啟;START_STICKY 表示服務會重啟,但不一定重送舊 Intent;START_REDELIVER_INTENT 則會重新投遞最後一次 Intent,適合不可中斷的任務。

啟動、停止與前台服務

呼叫 startService 後,系統會先執行 onCreate,再執行 onStartCommand。若要停止服務,可由服務呼叫 stopSelf,或由其他元件呼叫 stopService。若服務需要讓使用者明確感知,例如音樂播放,可呼叫 startForeground 並提供常駐通知。

以下是最基本的啟動寫法:

Intent intent = new Intent(this, HelloService.class);
startService(intent);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved