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

ApiDemos 解析(43):遠端 Service 的 Started 模式

編輯:Android 開發教學

Remote Service Controller 與先前解析過的 Local Service Controller 都採用 Service 的 Started 模式,兩者在生命週期管理上完全一致,差別只在於 RemoteService 跑在另一個行程裡。

在 manifest 中的宣告

關鍵是 android:process=":remote" 這個屬性,它讓該服務被配置到一個獨立行程:

<service android:name=".app.RemoteService" android:process=":remote">
<intent-filter>
  <!-- 服務支援的介面,可被打綁 -->
  <action android:name="com.example.android.apis.app.IRemoteService" />
  <action android:name="com.example.android.apis.app.ISecondary" />
  <!-- 用於在不指定實作類別的情況下選取服務 -->
  <action android:name="com.example.android.apis.app.REMOTE_SERVICE" />
</intent-filter>
</service>

啟動與停止

RemoteService.Controller 中的相關程式碼,比 Bound 模式要簡單得多:

// 確保服務已啟動,它會持續執行直到有人呼叫 stopService()
// 這裡用 action code 而非明確的元件名稱,
// 好讓其他套件可以替換這個服務的實作
startService(new Intent("com.example.android.apis.app.REMOTE_SERVICE"));

// 取消先前的 startService 呼叫。
// 注意:若仍有用戶端處於綁定狀態,服務不會真的停下來
stopService(new Intent("com.example.android.apis.app.REMOTE_SERVICE"));

Started 模式的特性是「一旦啟動就自己跑到底」,必須有人明確呼叫 stopService 才會結束。因此在按下 Start Service 之後,再去執行 ApiDemos 解析(42)中介紹的 Remote Service Binding 來綁定這個服務,你會發現「Received from Service」的初始值通常不是 1——因為服務早已在背景累計過若干次呼叫了。

這個現象剛好說明了 Started 與 Bound 在概念上的根本差異:前者的生命週期由啟動者與停止者的配對決定,與綁定數量無關;後者則隨綁定用戶端的數量自動伸縮。

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