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

Android Service 服務完整指南:分類、生命週期與使用時機

編輯:關於 Android 程式設計

上一篇談到通知欄 Notification,說到通知欄就不得不提 Service 與 BroadcastReceiver。作為 Android 四大元件中的兩員,它們幾乎無所不在地讓我們的程式與網路、資料庫、系統服務互動,再把結果透過 UI(通知欄就是一種呈現方式)展現出來。若把整個系統比作人體,它們就像神經系統;其中廣播接收器扮演傳輸者與監聽者,把系統的細微變化即時回報並觸發反應。

接下來這幾篇會依序說明 BroadcastReceiver、Service,以及兩者之間如何搭配。本篇先從官方文件、原始碼與筆記出發,把 Service 這個類別梳理清楚。

什麼是服務?

可以粗略地把 Service 想成一個沒有畫面、在後台默默工作的 Activity。它並不是獨立程序,而是依附在宿主程序的執行緒上;你只需要告訴它「要做什麼」,剩下的交給它執行。

由於沒有介面,Service 要與使用者互動時必須借助通知欄或廣播,再由 UI 呈現結果。它的應用範圍非常廣,尤其在框架層,大量場合其實是在呼叫系統服務。

服務能解決什麼問題

它適合承載那些不該干擾使用者操作的後台工作,例如檔案下載、網路抓取、背景播放音樂。Service 可以由 Intent 啟動,也可以綁定到宿主元件(例如 Activity)上共同運作。

官方定義概述

Service 是一種代表應用程式執行長時間作業的元件,它不直接與使用者互動,也不為其他應用提供介面。每個 Service 都必須在 AndroidManifest.xml 中以 <service> 標籤宣告,並透過 Context.startService() 或 Context.bindService() 啟動。與其他應用元件相同,它運行於宿主程序的/ui 執行緒。

類別結構

extends ContextWrapper / implements ComponentCallbacks2

java.lang.Object → android.content.Context → android.content.ContextWrapper → android.app.Service

已知的直接子類包含 AbstractInputMethodService、AccessibilityService、DreamService、IntentService、MediaRouteProviderService、NotificationListenerService、PrintService、RecognitionService、RemoteViewsService、SpellCheckerService、TextToSpeechService、VpnService、WallpaperService 等;間接子類則有 InputMethodService。

挑幾個常見的說明:

InputMethodService:提供輸入法的標準實作基礎,一般應用開發者用不到,主要是輸入法廠商與 ODM 夥伴的領域。

IntentService:專為處理非同步請求而設計,所有請求在一個工作執行緒(HandlerThread)中依序處理,任務做完執行緒即結束,不必自己管理併發。

MediaRouteProviderService:負責媒體路由的提供。

NotificationListenerService:與通知欄相關,用來接收系統通知的發布與移除事件。

RecognitionService:抽象服務類,想實作新的語音辨識引擎時會用到。

服務的分類

依使用範圍

1. 本地服務(Local Service)

用於應用程式內部。適合放耗時但不該佔用 UI 執行緒的工作,例如檢查版本更新,另開執行緒在後台執行以維持流暢體驗。

使用方式:以 Context.startService() 啟動、Context.stopService() 停止;Service 內部也可用 stopSelf() 或 stopSelfResult() 自行結束。無論呼叫多少次 startService(),只需一次 stopService() 即可停止。

2. 遠端服務(Remote Service)

供同一裝置內的不同應用程式共用,例如天氣查詢服務,其他 App 不必重複實作即可直接呼叫。

使用方式:定義並對外暴露介面(通常透過 AIDL)。用戶端以 Context.bindService() 建立連線並呼叫服務,用完以 Context.unbindService() 解除。多個用戶端可綁定同一個服務;若服務尚未載入,bindService() 會先將它載入。

依執行狀態

1. 前台服務

Android 2.0 以後呼叫 startForeground()(2.0 之前為 setForeground())即可把服務提升為前台服務,主要目的是避免服務在記憶體吃緊時被系統回收。

官方說明大意如下:前台服務是使用者能明確感知的服務,因此不是系統在記憶體不足時優先清除的對象。前台服務必須在狀態列顯示一則屬於「進行中」分類的通知,該通知無法被使用者手動滑除,除非服務被停止或退出前台狀態。典型例子是音樂播放器:使用者清楚知道音樂正在播放,狀態列的通知可以顯示目前曲目,並讓使用者點擊進入播放介面。

Notification notification = new Notification(R.drawable.icon,
        getText(R.string.ticker_text), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION, notification);

要退出前台狀態可呼叫 stopForeground(boolean),參數決定是否同時移除狀態列通知;這個方法並不會停止服務本身。若在服務仍處於前台時直接停止服務,通知也會一併消失。

實務上只要在 onStartCommand() 呼叫 startForeground(),並在 onDestroy() 呼叫 stopForeground() 即可。因此像音樂播放器這類服務,只要仍在播放,即使裝置休眠也不會被回收。

2. 後台服務

就是一般未提升為前台的服務,系統在資源不足時較容易將其回收。

生命週期

左圖為 startService 啟動方式的生命週期,右圖為 bindService 綁定方式的生命週期。

值得注意的是,早期文件中的 onStart 已被 onStartCommand 取代。Service 與 Activity 同為 Context 的派生類,可用 getApplicationContext() 取得上下文,兩者都有生命週期,但流程不同。

startService 流程:

context.startService() → onCreate() → onStartCommand() → Service running → context.stopService() → onDestroy()

簡化即:onCreate(僅建立時呼叫一次)→ onStartCommand(可重複呼叫多次)→ onDestroy。

onStartCommand(Intent, int flags, int startId) 會回傳一個整數,用來指示系統在服務被回收後該如何處理,常見值有 START_STICKY、START_STICKY_COMPATIBILITY、START_NOT_STICKY、START_REDELIVER_INTENT;flags 則可能是 START_FLAG_REDELIVERY 或 START_FLAG_RETRY。這種啟動方式下,服務不會因綁定元件被銷毀而跟著結束,適合下載、上傳等需要自行完成的工作。

另外,onCreate 只在首次建立時觸發,若服務已在執行,再次 startService() 會直接走到 onStartCommand()。可依需求把一次性初始化放進 onCreate(),把每次請求的處理放進 onStartCommand()。

bindService 流程:

context.bindService() → onCreate() → onBind() → Service running → onUnbind() → onDestroy()

簡化即:onCreate → onBind → onUnbind → onDestroy。此方式不會觸發 onStartCommand(),且只有在所有用戶端都解除綁定後,服務才會停止。透過 onBind() 回傳的 IBinder,用戶端得以呼叫服務的方法、取得服務實例或查詢狀態。此時呼叫者(例如 Activity)與 Service 綁在一起,呼叫者銷毀時才會依序觸發 onUnbind 與 onDestroy。

提醒:綁定的服務在元件銷毀前應確實解除綁定,否則容易造成記憶體洩漏。

第三種是透過 AIDL 進行跨程序通訊,本文不展開。

基本使用步驟

1. 建立服務類別

public class MyService extends Service {
}

2. 在 AndroidManifest.xml 註冊

<service android:name=".MyService"></service>

3. 啟動服務

直接啟動:

Intent intent = new Intent(getApplicationContext(), MyService.class);
startService(intent);
@Override
public void onCreate() { }

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // 在此接收 intent 攜帶的資料
    return START_STICKY;
}

@Override
public void onDestroy() { }

綁定啟動:

bindService(Intent service, ServiceConnection conn, int flags)

ServiceConnection 用來監聽服務狀態,常見的 flags 有:

Context.BIND_AUTO_CREATE:收到綁定請求時若服務尚未建立則立即建立;在系統需要釋放記憶體時,僅當該服務所在程序成為清除對象時才會被銷毀。

Context.BIND_DEBUG_UNBIND:主要用於除錯時驗證綁定是否正確,容易引發記憶體洩漏,非除錯用途不建議使用。

Context.BIND_NOT_FOREGROUND:阻止該服務所在程序取得前台優先級,僅在後台運行。

綁定是以非同步方式進行的,且必須在有效的 Context 環境中執行:

getApplicationContext().bindService(service, conn, flags);
boolean mIsBound = false;

public void doBindService() {
    bindService(new Intent(MainActivity.this, LocalService.class),
            mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;
}

public void doUnbindService() {
    if (mIsBound) {
        unbindService(mConnection);
        mIsBound = false;
    }
}

private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mBoundService = ((LocalService.LocalBinder) service).getService();
        Toast.makeText(MainActivity.this, "服務已連接", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mBoundService = null;
        Toast.makeText(MainActivity.this, "服務未連接", Toast.LENGTH_SHORT).show();
    }
};

服務端需要提供 Binder:

private final IBinder mBinder = new LocalBinder();

public class LocalBinder extends Binder {
    public LocalService getService() {
        return LocalService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

4. 停止服務

啟動型服務有兩種停止方式:stopSelf() 由服務自行結束,stopService(Intent) 由外部被動停止。綁定型服務則以 unbindService(ServiceConnection conn) 解除綁定。

實作細節提醒

1. 務必在 AndroidManifest.xml 中顯式宣告 Service,否則系統無法發現它。

2. 運算量大但不屬於 UI 層的工作,適合放進 Service。

3. Service 與呼叫者共用同一執行緒,並不會自動開新線程。因此若服務內要做 CPU 密集(如 MP3 轉碼)或阻塞型(如網路)操作,必須自行建立執行緒,否則會拖住/ui 執行緒。IntentService 就是這方面的標準示範。

4. 若 Service 搭配動態註冊的廣播接收器,記得在服務停止前呼叫 unregisterReceiver(receiver) 取消註冊。

延伸主題

如何判斷服務是否正在執行

private boolean isServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (com.example.MyService.class.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

Service 與 UI 的溝通方式

(1)startService + Intent:單向,UI → Service,在 onStartCommand() 中接收,寫法與 Activity 間傳值相同。

(2)bindService + IBinder:UI → Service,透過 Binder 直接呼叫服務方法。

(3)Broadcast:雙向,UI ↔ Service,註冊廣播接收器後即可互相發送訊息。服務退出時別忘了 unregisterReceiver()。

Service 與 Thread 的差別

很多人會問:既然只是要跑長時間背景任務,用 Thread 不就夠了,為何還要用 Service?關鍵在於兩者層次不同。

Thread 是程式執行的的最小單位,也是 CPU 排程的基本單位,適合跑非同步運算。Service 則是 Android 的元件機制:Local Service 運行在主程序的/ui 執行緒(onCreate、onStartCommand 等回呼都在該執行緒上被呼叫),Remote Service 則運行在獨立程序的/ui 執行緒。因此 Service 與 Thread 並非同一概念,不能互相取代。

之所以需要 Service,與 Android 的元件生命週期有關。Thread 的生命獨立於 Activity:Activity finish 之後,若沒有主動中止 Thread,它仍會繼續跑,此時你已失去對它的參考,也無法從另一個 Activity 去控制同一個 Thread。若你的需求是「無論哪個 Activity 在前台,都要持續定時與伺服器同步」,那麼把 Thread 放進 Service 中建立與管理,就是合理的解法——任何 Activity 都能透過 Context 的 startService、stopService、bindService、unbindService 來控制它,也可以在 Service 中註冊 BroadcastReceiver,由外部發送廣播遙控。這些都是裸 Thread 做不到的。

Service 的整理就到這裡,若有疏漏或想補充的地方歡迎指正。

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