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

Android Service 完全解析:分類、生命週期與 Bound 服務實作

編輯:關於 Android 程式設計

Service 是 Android 四大元件之一,也是最容易被誤解的一個。最常見的錯誤認知是「Service 就是背景執行的執行緒」——事實上兩者毫無繼承關係,Service 只是一種受系統管理的元件機制。本文從分類談起,接著釐清 Service 與 Thread 的差異,最後說明生命週期與實際的綁定寫法。

一、Service 的分類

依執行位置:Local 與 Remote

本地服務(Local)依附在主行程上,因為同行程所以不需要 IPC,也不必處理 AIDL,bindService 寫起來單純許多,同時省下行程資源。缺點是主行程被回收時,服務也一起消失。音樂播放器之類的應用大多屬此類。

遠程服務(Remote)跑在獨立行程,行程名為 package 名加上 manifest 中 android:process 指定的字串。因為行程獨立,即使 Activity 所在行程被結束,服務仍在背景存活,適合需要長期常駐或跨行程提供能力的場景。代價是額外的行程資源,以及必須透過 AIDL 進行跨行程溝通,實作較繁瑣。實務上純 Remote 服務並不常見,多為系統層級的服務。

依執行型態:前台與背景

前台服務會在通知欄顯示持續性的(ONGOING)通知,服務結束時通知也一併消失,使用者能清楚感知其存在,適合音樂播放、導航這類需要被看見的常駐工作。

背景服務是預設型態,不會在通知欄留下任何提示,服務結束時使用者也不會察覺,適合天氣更新、日曆同步、郵件同步這類安靜執行的工作。

要注意的是:單純自己 new 一個 ONGOING 通知並不會讓服務變成前台服務。必須額外呼叫 startForeground()(Android 2.0 以後)或 setForeground()(2.0 以前)才算。這樣做的好處是,當系統因故強制終止服務時,通知欄的項目也會被正確移除,不會留下「幽靈通知」。

依使用方式:start 與 bind

startService() 啟動的服務,目的在執行一項背景任務、不需要與元件雙向溝通,停止時用 stopService()。bindService() 啟動的服務則是為了取得連線並互相呼叫,停止時用 unbindService()。若兩者併用,則必須 stopService() 與 unbindService() 都呼叫過,服務才會真正結束。

二、Service 和 Thread 到底差在哪

Thread 是程式執行的最小單位,也是 CPU 調度的基本單位,用來跑非同步工作。Service 則是 Android 的元件機制:Local Service 的 onCreate、onStart 等回呼都跑在主行程的 main 執行緒上,Remote Service 則跑在獨立行程的 main 執行緒上。也就是說,Service 本身完全不具備背景執行緒的能力,若你在 Service 裡做耗時運算而沒有另開執行緒,一樣會 ANR。

那為什麼不直接用 Thread?問題出在生命週期與可達性。Thread 的存活獨立於 Activity,Activity finish() 之後若未主動停止,Thread 仍會繼續跑,此時你已失去對它的參考,也無法從其他 Activity 控制同一個 Thread。

舉例來說:假設有個 Thread 需要每隔一段時間連上伺服器做同步,即使目前沒有任何 Activity 可見也必須持續運作。當使用者開啟另一個 Activity 時,你完全無法在那個 Activity 裡控制先前建立的 Thread。改用 Service 就解決了這個問題——任何 Activity 都能透過 Context.startService / stopService / bindService / unbindService 控制同一個 Service,而系統保證只會有一份實例。你也可以在 Service 中註冊 BroadcastReceiver,從任何地方發送廣播來指揮它。這些都是 Thread 做不到的。

換個角度想,Service 更像一個「服務端點」:它有自己的生命週期、能被多個客戶端共享、能提供遠端介面。而「背景執行」這件事,仍然要交給 Thread、Executor 或(在較新版本上)WorkManager 來完成。

三、生命週期

四個主要回呼:onCreate、onStart(2.0 以後為 onStartCommand)、onDestroy、onBind。

被 startService 啟動

只要呼叫過 startService(),無論是否有元件 bind 過來,服務都會在背景持續執行。若被多次啟動,onCreate() 只會呼叫一次,onStart() 則依啟動次數被呼叫多次,且系統僅有一份實例(因此理論上只需一次 stopService())。服務會一直存活,直到有人呼叫 stopService() 或服務自行呼叫 stopSelf(),或者系統因資源不足而回收。

被 bindService 綁定

不論呼叫幾次 bindService(),onCreate() 只會被呼叫一次,而 onStart() 永遠不會被呼叫。連線建立後服務持續運行,直到呼叫 unbindService(),或先前 bind 的 Context 不復存在(例如 Activity 被 finish),系統會自動停止服務並觸發 onDestroy()。

同時被啟動又被綁定

服務會一直在背景執行。onCreate() 依然只呼叫一次,onStart() 依 startService 次數呼叫。此時單獨呼叫 unbindService() 並不會停止服務,必須再呼叫 stopService() 或 stopSelf() 才行。

清除工作

服務被終止時(stopService()、stopSelf(),或已無任何綁定連線且未被啟動)會觸發 onDestroy()。在這裡應該做收尾:停止在服務中建立的執行緒、釋放資源、取消未完成的 Callback。

五個實務陷阱

一、呼叫 bindService() 之後,務必在適當位置(例如 onDestroy())配對呼叫 unbindService()。雖然 Activity finish 時系統會自動解除,主動解除才是良好習慣。

二、用 startService() 啟動後,無論是否也用了 bind,都必須以 stopService() 收尾。

三、兩者併用時,先呼叫 unbindService() 服務不會結束,要再 stopService() 才行;反之先 stopService() 也不會結束,需等 unbindService() 或綁定的 Context 消失後才停止。

四、螢幕旋轉時 Activity 會被重建,原先 bind 建立的連線因此斷開(Context 已不存在),服務行為等同上述規則。

五、SDK 2.0 以後 onStart 已被 onStartCommand 取代(舊方法仍可用但已不建議)。新專案請直接實作 onStartCommand,並記得回傳 START_STICKY 或 START_NOT_STICKY 以決定被回收後的重建策略。

四、用 startService 啟動服務

不論 Local 或 Remote,startService 的寫法一樣簡單,別忘了在 AndroidManifest.xml 註冊服務。

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class LocalService1 extends Service {

    /**
     * onBind 是抽象方法,必須實作。
     * 回傳 null 表示不允許客戶端建立連線。
     */
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

啟動與停止的呼叫方式:

// 啟動服務
startService(new Intent(this, LocalService1.class));

// 停止服務
stopService(new Intent(this, LocalService1.class));

五、Local 服務的綁定

Local Service 的綁定相當單純:在 Service 中實作 onBind(),回傳一個 IBinder 物件即可。實務上我們直接繼承 Binder(它已實作了 IBinder 介面),省下大量樣板程式。

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class LocalService extends Service {

    /**
     * 直接繼承 Binder 而非實作 IBinder,因為 Binder 已完成實作。
     */
    public class SimpleBinder extends Binder {

        /** 取得 Service 實例 */
        public LocalService getService() {
            return LocalService.this;
        }

        public int add(int a, int b) {
            return a + b;
        }
    }

    public SimpleBinder sBinder;

    @Override
    public void onCreate() {
        super.onCreate();
        sBinder = new SimpleBinder();
    }

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

關鍵就在 onBind() 回傳了這個 Binder 物件,Activity 拿到它之後就能直接呼叫 Service 對外暴露的方法。Activity 端的寫法如下:

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;

public class Main extends Activity {
    private final static String TAG = "SERVICE_TEST";
    private ServiceConnection sc;
    private boolean isBind;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        sc = new ServiceConnection() {
            @Override
            public void onServiceDisconnected(ComponentName name) { }

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                LocalService.SimpleBinder sBinder = (LocalService.SimpleBinder) service;
                Log.v(TAG, "3 + 5 = " + sBinder.add(3, 5));
                Log.v(TAG, sBinder.getService().toString());
            }
        };

        findViewById(R.id.btnBind).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                bindService(new Intent(Main.this, LocalService.class), sc,
                        Context.BIND_AUTO_CREATE);
                isBind = true;
            }
        });

        findViewById(R.id.btnUnbind).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isBind) {
                    unbindService(sc);
                    isBind = false;
                }
            }
        });
    }
}

Activity 透過 ServiceConnection 接收「連線建立」與「連線意外中斷」的回呼。bindService() 有三個參數:辨識服務用的 Intent、實作 ServiceConnection 的物件,以及旗標。常用旗標為 BIND_AUTO_CREATE(連線時自動建立服務),另有 BIND_DEBUG_UNBIND 供除錯使用。unbindService() 的參數就是先前那個 ServiceConnection 物件。

要特別注意:重複對同一個連線呼叫 unbindService() 會丟出例外,因此範例中刻意用一個 boolean 變數記錄狀態。此外,若 onBind() 回傳 null,bindService() 仍會啟動服務但無法建立連線,onServiceConnected 不會被觸發,此時你依然需要呼叫 unbindService() 才能讓服務停止。

Remote 服務的綁定因為跨行程,必須動用 Android 的 IPC 機制與 AIDL,涉及介面定義、Stub/Proxy 模型與執行緒安全等議題,建議另立主題深入探討。

六、建立前台服務

在 SDK 2.0 以後使用 startForeground() 與 stopForeground();若最低支援版本低於 2.0,為了向後相容,需要以反射方式呼叫新方法。以下範例示範了這種相容寫法:

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

public class ForegroundService extends Service {

    private static final Class[] mStartForegroundSignature = new Class[] {
            int.class, Notification.class};
    private static final Class[] mStopForegroundSignature = new Class[] {
            boolean.class};

    private NotificationManager mNM;
    private Method mStartForeground;
    private Method mStopForeground;
    private Object[] mStartForegroundArgs = new Object[2];
    private Object[] mStopForegroundArgs = new Object[1];

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

    @Override
    public void onCreate() {
        super.onCreate();
        mNM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        try {
            mStartForeground = ForegroundService.class.getMethod(
                    "startForeground", mStartForegroundSignature);
            mStopForeground = ForegroundService.class.getMethod(
                    "stopForeground", mStopForegroundSignature);
        } catch (NoSuchMethodException e) {
            mStartForeground = mStopForeground = null;
        }

        // 不需為 notification.flags 設定 FLAG_ONGOING_EVENT,
        // 前台服務的通知預設就包含該旗標。
        Notification notification = new Notification(R.drawable.icon,
                "Foreground Service Started.", System.currentTimeMillis());
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, Main.class), 0);
        notification.setLatestEventInfo(this, "Foreground Service",
                "Foreground Service Started.", contentIntent);

        // 注意:id 為 0 時通知不會顯示
        startForegroundCompat(1, notification);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopForegroundCompat(1);
    }

    /** 以相容方式啟動前台服務 */
    private void startForegroundCompat(int id, Notification n) {
        if (mStartForeground != null) {
            mStartForegroundArgs[0] = id;
            mStartForegroundArgs[1] = n;
            try {
                mStartForeground.invoke(this, mStartForegroundArgs);
                return;
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        setForeground(true);
        mNM.notify(id, n);
    }

    /** 以相容方式停止前台服務 */
    private void stopForegroundCompat(int id) {
        if (mStopForeground != null) {
            mStopForegroundArgs[0] = Boolean.TRUE;
            try {
                mStopForeground.invoke(this, mStopForegroundArgs);
                return;
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        // 先 cancel 再 setForeground(false):避免在兩者之間的一瞬間被回收,
        // 導致通知永遠留在通知欄。
        mNM.cancel(id);
        setForeground(false);
    }
}

(註:Notification.setLatestEventInfo() 與 setForeground() 在新版平台上已不建議使用,現行專案請改用 Notification.Builder 或 NotificationCompat.Builder 搭配 startForeground(id, notification),並記得在 targetSdk 26 以上需建立通知管道。)

七、該用哪一種啟動方式

若只是想啟動一個長期在背景執行的任務,startService() 就足夠。

若需要與執行中的服務溝通,有兩種選擇:一是廣播,二是 bindService()。廣播的缺點是溝通頻繁時容易拖累效能,且 BroadcastReceiver 的 onReceive() 執行時間受限,逾時後後續程式碼可能不再執行。因此高頻溝通應選擇 bindService()——此時你便同時在用 start 與 bind,這在 Activity 中更新服務執行狀態時非常實用。

若服務的用途只是對外公開一組遠端介面供客戶端呼叫,甚至可以不主動啟動,只用 bindService();服務會在第一次綁定時才建立實例,節省不少資源。若服務是 Remote Service,這個效果會更明顯(代價是首次建立連線需等待一段時間)。

八、Manifest 中的 Service 屬性

android:name       服務類別名稱
android:label      服務顯示名稱,未設定時預設為類別名稱
android:icon       服務圖示
android:permission 宣告此服務的權限,只有具備該權限的應用才能控制或連線
android:process    是否執行於另一行程,設定後會在 package 名後附加此字串
android:enabled    是否允許系統啟動此服務,未設定時預設為 false
android:exported   是否允許其他應用控制或連線,未設定時預設為 false

結語

Service 的價值不在「背景執行」,而在「被多個元件共享、由系統統一管理的長生命週期端點」。理解這點之後,就不會再犯「在 Service 的 onStart 裡直接跑網路請求」這類 classic 錯誤——正確做法是在 Service 中建立執行緒或工作佇列,把運算交給它,Service 本身只負責管理生命週期與對外介面。在 Android 8.0 以後,背景啟動限制與執行時間窗的限制更加嚴格,長時間的常駐工作應优先考虑 WorkManager 或前台服務搭配通知,這也是現代 Android 開發必須具備的判斷。

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