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

Android Service 全面解析:分類、生命週期與使用方式

編輯:關於 Android 程式設計

一、Service 的分類

依執行位置:本地服務與遠程服務

本地服務(Local)依附在主進程上,因此不必 IPC、也不用寫 AIDL,bindService 相對簡單,某種程度上也節省資源。缺點是主進程被砍掉時服務隨之終止。音樂播放服務就是最典型的例子。

遠程服務(Remote)跑在獨立進程中,進程名格式為「套件名 + android:process 指定的字串」。因為是獨立進程,Activity 所在進程被銷毀時它照樣運行,不受影響,也方便同時服務多個進程,靈活性高。代價是會佔用額外資源,而且 IPC 得靠 AIDL,寫起來麻煩一些。這類服務多半是常駐的系統服務,一般應用其實很少用到。

依執行型態:前台服務與後台服務

前台服務會在通知欄顯示一則 ONGOING 的通知,服務被終止時通知也會一起消失,對使用者有明確提示作用,音樂播放器最常見。

後台服務是預設形態,通知欄不會有任何提示,服務結束時使用者完全無感,適合天氣更新、日期同步、郵件同步這類不需要提示的常駐工作。

有人會問:我在後台服務裡自己發一則 ONGOING 通知,是不是就變成前台服務了?答案是否定的。真正的前台服務還必須呼叫 startForeground()(Android 2.0 以後)或 setForeground()(2.0 以前)。這樣做的好處是,當服務被外部強制終止時,那則 ONGOING 通知也會被一併移除,不會留下幽靈通知。

依啟動方式

  • startService:用來啟動服務執行後台任務,不做溝通,停止時呼叫 stopService。
  • bindService:用來與服務通訊,停止時呼叫 unbindService。
  • 兩者併用:停止時必須同時呼叫 stopService 與 unbindService。

二、Service 與 Thread 的差別

很多人會問:既然 Thread 寫起來更方便,為什麼還要用 Service?關鍵在於兩者根本不是同一層面的東西。

Thread 是程式執行的最小單位,也是 CPU 調度的基本單位,用來跑非同步任務。而 Service 是 Android 的一種元件機制:Local Service 的 onCreate、onStart 等回呼都跑在主進程的 main 執行緒上;Remote Service 則跑在獨立進程的 main 執行緒上。所以請不要把 Service 當成執行緒,兩者沒有任何繼承或包含關係。

那 Service 的價值在哪?在於它解決了 Thread 的生命週期難以管控的問題。Thread 的執行獨立於 Activity:Activity finish 之後,如果你沒有主動停掉 Thread,它還是會繼續跑,而你也不再持有它的參照;更麻煩的是,你沒辦法在不同 Activity 之間操作同一個 Thread。

舉例來說,假設有個 Thread 需要每隔一段時間連線伺服器做同步,即使目前沒有任何 Activity 可見也得持續運行。這時你在新開的 Activity 裡根本控制不到先前建立的 Thread。解法就是建立並啟動一個 Service,把 Thread 的建立、執行與控制都放進 Service 裡——因為任何 Activity 都能控制同一個 Service,而系統也只會維護一個 Service 實例。

換個角度想,Service 就像一個訊息服務:在任何有 Context 的地方都能用 Context.startService、stopService、bindService、unbindService 控制它,也可以在 Service 中註冊 BroadcastReceiver,由外部發送廣播來驅動。這些都是裸 Thread 做不到的。

三、Service 的生命週期

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

被啟動的服務

以 Context.startService 啟動後,無論是否有 Activity 綁定,服務都會在後台持續運行。若被多次啟動,onCreate 只會呼叫一次,onStart 則依啟動次數被呼叫多次,而系統僅維護一個 Service 實例(所以一次 stopService 就足夠)。服務會一直運行直到呼叫 stopService 或自身的 stopSelf,資源不足時系統也可能主動結束它。

被綁定的服務

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

同時被啟動與綁定的服務

這種情況下服務會一直在後台運行。onCreate 依然只呼叫一次,onStart 次數等同 startService 的次數。此時呼叫 unbindService 不會停止服務,必須再呼叫 stopService 或 stopSelf 才行。

服務停止時

當服務被終止(呼叫 stopService、呼叫 stopSelf、或不再有任何綁定連線且未曾被啟動)時,onDestroy 會被觸發,應該在這裡進行清理,例如停止在 Service 中建立的執行緒。

特別注意

  1. 呼叫 bindService 之後,務必在某處對應呼叫 unbindService(即使 Activity finish 時會自動解除綁定並停止服務)。
  2. 用 startService 啟動後,一定要用 stopService 停止,無論你是否也用了 bindService。
  3. 兩者併用時,必須 unbindService 與 stopService 都呼叫過,服務才會真正終止,且與呼叫順序無關:先 unbind 服務不會停,再 stopService 才停;先 stopService 服務也不會停,之後 unbind(或 bind 的 Context 消失)才會自動停止。
  4. 旋轉螢幕時,若 Activity 會自動旋轉,那其實是 Activity 的重建,先前用 bindService 建立的連線會因此斷開(Context 不存在了),後續生命週期同上。
  5. SDK 2.0 以後 onStart 已被 onStartCommand 取代,舊的仍然可用,但新專案請直接用 onStartCommand。

四、以 startService 啟動服務

不論 Local 還是 Remote,用 startService 啟動的步驟一樣簡單,別忘了在 AndroidManifest.xml 註冊服務。依生命週期可寫出如下框架:

package com.newcj.test;

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 void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
startService(new Intent(this, LocalService1.class));
// ...
stopService(new Intent(this, LocalService1.class));

五、Local 與 Remote 服務的綁定

一樣要先在 AndroidManifest.xml 註冊服務。

Local 服務綁定

Local 的綁定比較單純:在 Service 中實作 onBind,回傳一個實作 IBinder 介面的物件。由於 Binder 已經實作了 IBinder,直接繼承 Binder 可以少寫很多東西:

package com.newcj.test;

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

public class LocalService extends Service {

    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(Intent) 回傳了實作 IBinder 的物件,Activity 靠它與 Service 溝通。Activity 側的程式碼:

package com.newcj.test;

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(與 startService 相同)、ServiceConnection 實作物件,以及 flag。flag 有 BIND_DEBUG_UNBIND(供除錯用)與 BIND_AUTO_CREATE(一般使用)兩種。unbindService 的參數則是先前那個 ServiceConnection 物件。要留意:重複 unbind 同一個連線會丟出異常,因此範例用了一個 boolean 變數記錄是否已解除綁定。

Remote 服務綁定

Remote 服務跑在另一個進程,必須動用 Android 的 IPC 機制與 AIDL,細節牽涉廣泛,此處先不展開。

特別注意:若 Service.onBind 回傳 null,bindService 仍會啟動服務但無法建立連線,因此 ServiceConnection.onServiceConnected 不會被呼叫;不過你依然必須呼叫 unbindService 斷開,服務才會停止。

六、建立前台服務

SDK 2.0 以後用 startForeground 與 stopForeground,之前的版本則是 setForeground。若程式的最高相容門檻是 2.0,直接用新方法即可;若必須向下相容,就得靠反射來呼叫。以下程式碼示範了這種相容處理:

package com.newcj.test;

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 時 notification 不會顯示
        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);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return;
        }
        setForeground(true);
        mNM.notify(id, n);
    }

    /** 以相容方式停止前台服務 */
    private void stopForegroundCompat(int id) {
        if (mStopForeground != null) {
            mStopForegroundArgs[0] = Boolean.TRUE;
            try {
                mStopForeground.invoke(this, mStopForegroundArgs);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            return;
        }
        // 先 cancel 再 setForeground(false):否則若正好在此瞬間被砍,
        // 通知會永遠留在通知欄
        mNM.cancel(id);
        setForeground(false);
    }
}

七、該用 startService 還是 bindService?

只是想啟動一個長期在後台跑任務的服務,startService 就夠了。

如果需要與執行中的 Service 溝通,有兩條路:一是廣播,二是 bindService。廣播的問題在於溝通頻繁時會拖累效能,而且 BroadcastReceiver 的執行時間很短(很可能還沒跑完就被回收),bindService 沒有這些顧慮,所以應該選 bindService——此時你其實同時在用 startService 與 bindService,這在 Activity 更新 Service 執行狀態時非常實用。

另一種情況:服務只是對外公開一個遠端介面,等客戶端連上才做事。這時可以完全不主動啟動,只用 bindService,等第一次綁定時才建立服務實例,能省下不少資源——服務若是 Remote Service,效果會更明顯。當然,服務建立本身需要時間,這點要納入考量。

八、AndroidManifest.xml 中 Service 的常見屬性

  • android:name —— 服務類別名稱
  • android:label —— 服務顯示名稱,不設定則顯示類別名
  • android:icon —— 服務圖示
  • android:permission —— 宣告此服務的權限,只有具備該權限的應用才能控制或連線
  • android:process —— 指定服務執行於另一個進程,值會接在套件名後作為進程名
  • android:enabled —— 設為 true 時系統會預設啟動它,不設定則為 false
  • android:exported —— 是否允許其他應用控制或連線此服務,預設 false
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved