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

Android Service 完全解析:分類、生命週期與啟動方式的選擇

編輯:關於 Android 程式設計

四大元件裡,Service 是很多人自認「用過但其實沒搞懂」的一個。它看起來像背景程式,又常被誤認為是執行緒,理解偏差往往要到出問題那天才發現。這篇就把它一次講清楚。

Service 的種類

按運行位置分類

三種啟動方式對應的生命週期並不相同,下面會逐一說明。

Service 和 Thread 不是同一回事

很多人會問:既然 Thread 用起来更方便,為什麼還要用 Service?先把兩者的定位說清楚。

Thread 是程式執行的最小單位,也是 CPU 調度的基本單位,通常用來跑非同步工作。
Service 是 Android 的一種元件機制。如果是 Local Service,它跑在主進程的 main 執行緒上——onCreate、onStart 這些回呼被系統呼叫時,都在 main 執行緒;如果是 Remote Service,則跑在獨立進程的 main 執行緒上。

所以答案很明確:Service 不是執行緒,兩者沒有任何繼承或包含關係。把 Service 理解成「一個比較長壽的元件」,比理解成「一個比較特殊的執行緒」更接近事實。

那 Service 的價值在哪?關鍵在於它的生命週期獨立於 Activity。Thread 雖然也獨立於 Activity,但問題恰恰出在這裡:Activity finish 之後你不再持有那個 Thread 的參照,也無法從另一個 Activity 去控制它。

舉個具體場景:你的 Thread 需要每隔一段時間連一次伺服器做同步,而且必須在 Activity 不在前台時持續運行。這時你沒有辦法在新開的 Activity 裡控制先前建立的 Thread。解法就是把 Thread 建在 Service 裡——因為任何 Activity 都能控制同一個 Service,而系統也只會維持一個 Service 實例。

換個角度想,Service 更像一個「服務端點」:任何有 Context 的地方都能呼叫 startService、stopService、bindService、unbindService 來控制它;也可以在 Service 裡註冊 BroadcastReceiver,由外部發送廣播來指揮它。這些都是裸 Thread 做不到的。

生命週期:四個回呼,三種劇本

核心回呼只有四個:onCreate、onStart(2.0 之後為 onStartCommand)、onDestroy、onBind。差異全在啟動方式。

劇本一:被 startService 啟動
只要呼叫過 startService,無論是否有 Activity 綁定,Service 都會在背景持續運行。多次呼叫 startService,onCreate 只會執行一次,onStart 則依呼叫次數觸發多次,且系統只會建立一個 Service 實例——所以停止時只需一次 stopService。它會一直待到被 stop 或自身呼叫 stopSelf,除非系統資源不足而將其回收。

劇本二:被 bindService 綁定
不論呼叫幾次 bindService,onCreate 都只執行一次,而 onStart 完全不會被呼叫。連線建立後 Service 持續運行,直到呼叫 unbindService,或先前綁定的 Context 不復存在(例如 Activity finish),系統才會停止它並觸發 onDestroy。

劇本三:啟動又被綁定
這種情況下 Service 會一直在背景運行。onCreate 永遠只呼叫一次,onStart 則隨 startService 次數觸發。此時呼叫 unbindService 不會停止 Service,必須再搭配 stopService 或 stopSelf。

善後:onDestroy
當 Service 被終止(stopService、stopSelf,或不再有綁定連線且未曾啟動)時,onDestroy 會被呼叫。在這裡應該做清理工作,例如停掉在 Service 中建立並運行的執行緒。

幾個容易忽略的注意事項

1. 呼叫 bindService 之後,務必在某處對應地呼叫 unbindService。雖然 Activity finish 時綁定會自動解除、Service 也會自動停止,但主動解除才是清楚的寫法。
2. 用 startService 啟動後,一定要用 stopService 停止,不管你另外有沒有 bindService。
3. 同時使用兩者時,Service 的終止需要 unbindService 與 stopService 都被呼叫。不論順序如何,單獨呼叫其中一個都不會讓 Service 停下。
4. 旋轉螢幕時,若 Activity 會自動旋轉,那其實是 Activity 的重建,先前以 bindService 建立的連線會因此斷開(Context 已不存在),Service 的後續行為與劇本二相同。
5. SDK 2.0 起,onStart 已被 onStartCommand 取代。舊方法雖然仍可用,但新專案請直接用 onStartCommand。

用 startService 啟動服務

無論 Local 還是 Remote,用 startService 啟動的準備工作都一樣簡單,別忘了在 AndroidManifest.xml 註冊即可。依據上面的生命週期,Service 的骨架長這樣:

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));

這裡的 Intent 是明確 Intent,用來標示目標 Service 類別。

綁定 Local Service

綁定模式的重點在 onBind:必須回傳一個實作 IBinder 的物件,作為 Activity 與 Service 之間的溝通通道。實務上直接繼承 Binder 更省事,因為 Binder 已經實作了 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;
    }
}

Activity 側則透過 ServiceConnection 接收「連線建立」與「連線意外中斷」兩個回呼:

public class Main extends Activity {

    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("SERVICE_TEST", "3 + 5 = " + sBinder.add(3, 5));
                Log.v("SERVICE_TEST", 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;
                }
            }
        });
    }
}

bindService 有三個參數:標示目標 Service 的 Intent(與 startService 用的一致)、實作 ServiceConnection 的物件,以及 flag。有 BIND_DEBUG_UNBIND(供除錯)與 BIND_AUTO_CREATE(一般使用)兩種。unbindService 的參數則是先前那個 ServiceConnection 物件。

這裡有個實務陷阱:對同一個連線重複呼叫 unbindService 會丟出例外,所以我用一個 boolean 變數記錄是否已解除綁定。

另外,若 onBind 回傳 null,bindService 仍會啟動 Service,但連線建立不起來,onServiceConnected 不會被呼叫——此時你還是需要呼叫 unbindService,否則 Service 不會停止。

Remote Service 的綁定因為跨進程,需要動用 Android 的 IPC 機制,細節會在另一篇專文說明。

建立前台服務

前台服務會在通知列持續顯示,被系統回收的機率顯著降低,適合下載、播放音樂這類使用者能感知的長時間任務。SDK 2.0 起改用 startForeground 與 stopForeground;若最低支援版本低於 2.0,就得用反射呼叫新方法以保持向後相容。

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;
        }

        // 前台服務的通知會自動帶上 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);
            } catch (Exception 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 (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        // 先 cancel 再 setForeground(false):避免在兩者之間被 kill 掉,
        // 導致通知永遠留在通知欄
        mNM.cancel(id);
        setForeground(false);
    }
}

該用哪一種?決策指南

只想讓某件事在背景長期跑 → 用 startService 即可。
需要與執行中的 Service 溝通 → 有兩條路:廣播或 bindService。廣播的弱點是溝通頻繁時效能差,而且 BroadcastReceiver 的 onReceive() 執行時間很短,程式碼可能跑不完就被回收。因此正式專案通常選 bindService——此時你其實同時在用 startService 與 bindService,這在 Activity 更新 Service 運行狀態時非常有用。
Service 只是提供一個遠端介面供他人呼叫 → 可以只用 bindService,讓 Service 在第一次綁定時才建立實例,省下不少資源,Remote Service 的效果尤其明顯。代價是首次建立需要時間,這點要納入考量。

AndroidManifest.xml 中的常見屬性

· android:name:Service 的類別名稱
· android:label:Service 顯示名稱,不設則顯示類別名
· android:icon:Service 圖示
· android:permission:宣告此 Service 的權限,只有具備該權限的應用才能控制或連線
· android:process:指定 Service 運行於另一個進程,值會附加在包名之後作為進程名
· android:enabled:設為 true 時 Service 可被系統啟動,未設定則預設為 false
· android:exported:是否允許其他應用控制或連線,未設定則預設為 false

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