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

ApiDemos 解析(38):前台 Service 與 Service 基礎概念

編輯:Android 開發教學

Android 的 Service 與 Windows 中的服務概念相近:都沒有使用者介面,都在背景執行。Activity 可以啟動一個 Service,而 Service 一旦啟動便能持續在背景存活,即使啟動它的 Activity 被關閉或切換走了也不受影響。

Service 的兩種存在形式

Started:透過 startService() 啟動。啟動後不受啟動者控制,適合在背景執行費時工作,如下載檔案,通常不會把結果回傳給啟動它的 Activity。

Bound:透過 bindService() 啟動。它提供了一種 Client/Service 的互動模型,允許呼叫方與服務雙向溝通:發送請求、取得結果,並支援行程間溝通。Bound Service 的生命週期與綁定它的 Activity 連動,多個 Activity 可同時綁定同一個服務,當所有綁定都解除時,服務自動結束。

這兩種形式只是為了說明方便,實際上同一個 Service 可以同時具備兩種身分,只要把兩組介面該實作的函式都寫好即可。

核心方法

onStartCommand():Activity 呼叫 startService 時觸發。由於此類服務不受啟動者控制,應用有責任主動停止它,服務也可以呼叫 stopSelf 自行結束。

onBind():Activity 呼叫 bindService 時觸發,需回傳一個 IBinder 物件給呼叫方,對方再透過它提供的介面來使用服務。

onCreate():服務第一次被建立時呼叫,性質與 Activity 的 onCreate 類似。

onDestroy():服務退出時呼叫。

實作完 Service 子類別後,和 Activity 一樣必須在 AndroidManifest.xml 中宣告:

<manifest ... >
...
<application ... >
 <service android:name=".ExampleService" />
...
</application>
</manifest>

同樣可以為 Service 設定 Intent Filter;若不希望被外部存取,把 android:exported 設為 false 即可。

何謂前台 Service

Service 通常隱身在背景,但 Android 也允許它站到前台。前台服務必須在螢幕頂端狀態列提供一個 Notification,明確告知使用者「有東西正在跑」,例如音樂播放器在標題欄顯示當前曲目就是典型例子。

本例的 Foreground Service Controller 示範了一個跑在前台的服務,做法是呼叫 startForeground() 切到前台、stopForeground() 退出前台(注意:這只會讓它離開前台,服務本身不會停止)。這兩個方法是 API 2.0 才加入的,之前的版本只有 setForeground。

為了同時相容舊版,本例用反射的方式動態探測當前系統是否具備 startForeground 與 stopForeground,有就呼叫,沒有就退回 setForeground。相關的方法簽章與參照宣告如下:

private static final Class[] mStartForegroundSignature = new Class[] {
  int.class, Notification.class};
private static final Class[] mStopForegroundSignature = new Class[] {
  boolean.class};
private Method mStartForeground;
private Method mStopForeground;
private Object[] mStartForegroundArgs = new Object[2];
private Object[] mStopForegroundArgs = new Object[1];

你只要知道 startForegroundCompat 與 stopForegroundCompat 的作用等同於 startForeground 與 stopForeground 即可,其餘反射細節與 Service 本身的邏輯無關。值得一提的是,在後續的 Android 版本中,啟動前台服務已成為強制要求,並需要搭配通知渠道(Notification Channel)使用。

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