Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

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

編輯:Android 開發實例

Service 是 Android 四大元件之一,但也最常被誤解成「執行緒」。這篇把它的分類、與 Thread 的差異、生命週期、啟動與綁定方式,以及 manifest 常見屬性一次講清楚。

一、Service 的分類

依執行位置:

本機服務(Local)依附在主進程上。因為與 Activity 同處一個進程,不需要 IPC、也不需要 AIDL,bindService 寫起來簡單,資源佔用也較少;缺點是主進程被 kill 後服務也跟著結束。HTC 與天天動聽的音樂播放服務都屬於這類。

遠端服務(Remote)跑在獨立進程,行程名稱為套件名加上 manifest 中指定的 android:process 字串。即使 Activity 所在的進程被結束,它仍能繼續運行,適合為多個進程提供服務,靈活度高;代價是佔用資源較多,且需用 AIDL 做跨進程溝通,寫起來麻煩些。實際上這類服務多為系統常駐服務,一般應用中並不常見。

依執行型態:

前台服務會在通知列顯示 ONGOING 的常駐通知,服務被終止時通知也一併消失,對使用者有明確提示作用,音樂播放是最典型的例子。

背景服務是預設型態,不會在通知列顯示任何提示,服務結束時使用者完全無感,適合天氣更新、日期同步、郵件同步這類不需要提示的工作。

有些人會問:自己在背景服務裡丟一個 ONGOING 通知,是不是就變成前台服務了?並不是。真正成為前台服務必須再呼叫 startForeground()(Android 2.0 以後)或 setForeground()(2.0 以前)。這樣做的好處是,當服務被外部強制終止時,通知欄的項目也會確實被移除,不會留下幽靈通知。

依使用方式:

用 startService 啟動的服務,主要用來執行背景任務、不做溝通,停止時呼叫 stopService。

用 bindService 啟動的服務,重點在於通訊,停止時呼叫 unbindService。

若兩者併用,則必須 stopService 與 unbindService 都呼叫過,服務才會真正停止。

二、Service 與 Thread 到底差在哪

Thread 是程式執行的最小單元,也是 CPU 調度的基本單位,用來跑非同步操作很方便。

Service 則是 Android 的一種機制。若是 Local Service,它運行在主進程的 main 執行緒上,onCreate、onStart 這些回呼都在 main 執行緒被觸發;若是 Remote Service,則跑在獨立進程的 main 執行緒上。所以別把 Service 當成執行緒,兩者沒有直接關係。

那為什麼不直接用 Thread?問題出在生命週期與可控制性。Thread 的存活獨立於 Activity:Activity finish 之後,若沒有主動停止、run 方法也還沒跑完,Thread 會繼續執行,此時你已經失去對它的參考,也無法從另一個 Activity 去控制同一個 Thread。

舉個情境:假設需要一個執行緒每隔一段時間就連上伺服器做同步,而且即使目前沒有任何 Activity 可見也必須持續運行。這時新開的 Activity 根本拿不到先前那個 Thread 的參照。合理的做法是建立並啟動一個 Service,把 Thread 的創建、運行與控制都放進去——因為任何 Activity 都能控制同一個 Service,而系統也只會維持一個對應實例。

換個角度想,Service 比較像一種訊息服務:在任何有 Context 的地方都能用 startService/stopService/bindService/unbindService 控制它,也可以在 Service 裡註冊 BroadcastReceiver,由外部發送 broadcast 來驅動。這些都是單純 Thread 做不到的。

三、生命週期

核心回呼有 onCreate、onStart、onDestroy、onBind 四個。

被啟動的服務:一旦由 Activity 呼叫 startService 啟動,無論後續是否有 bind 或 unbind,服務都會在背景運行。若被多次 startService,onCreate 只會被呼叫一次,onStart 則對應每次 startService 的次數被呼叫多次,且系統只維持一個實例(所以一次 stopService 就夠了)。服務會持續運行,不受 Activity 存廢影響,直到有人呼叫 stopService 或服務自己呼叫 stopSelf;當然,系統資源不足時仍可能被回收。

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

同時被啟動與綁定的服務:服務會一直在背景運行。onCreate 永遠只呼叫一次,onStart 次數則等於 startService 的次數。單獨呼叫 unbindService 並不會停止服務,必須再搭配 stopService 或 stopSelf。

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

四、特別容易出錯的地方

一、呼叫 bindService 之後,務必在某處對應呼叫 unbindService。雖然 Activity finish 時綁定會自動解除、服務也會自動停止,但那是依賴 Context 消失的副作用,不是好習慣。

二、用 startService 啟動後一定要 stopService,無論你是否 ALSO 用了 bindService。

三、兩者併用時,必須 unbindService 與 stopService 都呼叫過才會終止,且與呼叫順序無關。先 unbind 時服務不會停,要等 stopService 之後才停;先 stopService 時服務也不會停,得等 unbind 或 bind 的 Context 消失後才自動停止。

四、旋轉螢幕時,若 Activity 會自動旋轉,那其實是 Activity 的重建,先前用 bindService 建立的連線會因此斷開(Context 不存在了),服務生命週期依前述規則走。

五、SDK 2.0 之後 onStart 已被 onStartCommand 取代(舊的仍可用)。如果你的最低支援版本是 2.0 以上,就該改用 onStartCommand。

五、以 startService 啟動服務

不論 Local 還是 Remote,寫法一樣簡單,別忘了在 AndroidManifest.xml 註冊 service。依據生命週期,骨架如下:

package com.newcj.test;

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

public class LocalService1 extends Service {
    /**
     * onBind 是 Service 的抽象方法,必須實作。
     * 回傳 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();
    }
}
startActivity(new Intent(this, LocalService1.class));
...
stopService(new Intent(this, LocalService1.class));

這裡的 Intent 只是用來標識目標服務類別。

六、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() 回傳的這個物件,它是 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 有三個參數:用來標識 Service 的 Intent、實作 ServiceConnection 的物件,以及 flag。flag 有 BIND_DEBUG_UNBIND(供除錯)與 BIND_AUTO_CREATE(一般採用)兩種。unbindService 的參數就是先前那個 ServiceConnection 物件。

要留意:重複呼叫 unbindService 釋放同一個連線會丟出例外,因此實務上會用一個 boolean 變數記錄是否已 unbind,避免重複呼叫。

執行結果:

Remote 服務綁定由於服務位於另一個進程,必須動用 Android 的 IPC 機制與 AIDL,細節牽涉廣泛,這裡先不展開。

另外補充一個容易忽略的點:若 onBind 回傳 null,bindService 仍會啟動 Service,但連線建立不起來,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 時通知不會顯示
        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;
        }
        // 在 setForeground 之前先 cancel,因為有可能在取消前台狀態的那一瞬間被 kill,
        // 導致通知永遠留在通知欄
        mNM.cancel(id);
        setForeground(false);
    }
}

再提醒一次:startForeground 的 id 若為 0,通知不會顯示。

八、該用 startService、bindService,還是兩者併用

只是單純想跑一個長期背景任務,用 startService 就足夠。

若需要與執行中的 Service 溝通,有兩條路:一是 broadcast,二是 bindService。前者的問題是溝通過於頻繁時容易拖累效能,而且 BroadcastReceiver 的執行時間很短(有可能 code 還沒跑完就被回收);後者沒有這些顧慮,因此通常選擇 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

把這些規則記牢,Service 的生命週期就不再是黑箱:誰啟動、誰綁定、誰該負責收尾,都能一一對應回程式碼。

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