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

Android 四大組件之 Service:啟動方式、生命週期與前台服務

編輯:關於 Android 程式設計

一、Service 的基本概念

四大組件都運行在主線程上。Service 是一種可以在不定時間內於後台運行、且不與使用者直接互動的應用組件,每個 Service 都必須在 manifest 中宣告,可透過 Context.startService() 或 Context.bindService() 啟動。

與其他應用組件一樣,Service 跑在進程的主線程中。這意味著:如果有耗時或阻塞的操作,必須在其子線程中實作,否則會直接拖住 UI。關於進程優先級,Android 大致分為五種:前台進程(使用者正在互動,相當於 Activity 執行 onResume)、可視進程(畫面仍看得見,相當於 onPause)、服務進程(透過 startService 啟動)、後台進程(畫面不可見,相當於 onStop)以及空進程。

二、Service 的定義

定義一個服務,就是寫一個類別去繼承 Service,並實作抽象方法 onBind()。若要處理實際業務,通常還會重寫三個方法:

@Override
public void onCreate() {
    // 服務第一次建立時呼叫
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // 每次服務被啟動時都會呼叫
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
    // 服務銷毀時呼叫
}

三者容易混淆的地方在於 onCreate 與 onStartCommand 的差別:onCreate 只在服務第一次建立時呼叫一次,而 onStartCommand 每次啟動服務都會被呼叫。

另外別忘了,每個服務都必須在 AndroidManifest.xml 中註冊:

三、啟動與停止服務

定義好自己的服務類之後,在主介面中透過按鈕點擊事件來啟動與停止:

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

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

這兩個方法都定義在 Context 類中,所以 Activity 裡可以直接呼叫,服務何時停止完全由 Activity 決定。如果想讓服務自己停下來,只要在服務類別中的任何位置呼叫 stopSelf() 即可。

可以這樣理解:Android 中的服務同樣運行於後台,只是它是「一個沒有界面的 Activity」。

四、兩種啟動模式的區別

需要强调的是,startService() 與 bindService() 並非完全互斥,兩者可以同時使用。

4.1 本地服務(Local Service)

用於應用程式內部。它以 Context.startService() 啟動,以 Context.stopService() 結束,也可以自行呼叫 stopSelf() 或 stopSelfResult() 停止。注意:無論呼叫了多少次 startService(),只需要呼叫一次 stopService() 就能停掉服務。

典型用途是實現應用自身的一些耗時任務,例如檢查版本更新。它在獨立線程中執行,不佔用 Activity 所屬線程,使用者體驗更好。

4.2 遠程服務(Remote Service)

用於 Android 系統內不同應用程式之間。它透過自訂並暴露的介面提供操作能力:客戶端用 Context.bindService() 建立連線,用 Context.unbindService() 關閉連線,多個客戶端可以綁定同一個服務;若服務尚未載入,bindService() 會先把它載入起來。

這種服務可被其他應用程式複用,例如天氣預報服務,其他 App 不必重寫一份,直接呼叫現有的即可。

五、生命週期

Service 無法自行運行,必須透過 Context.startService() 或 Context.bindService() 啟動。兩者都能啟動服務,但適用場合明顯不同。

5.1 startService 方式

呼叫者與服務之間沒有關聯,即使呼叫者退出,服務仍在運行。若服務尚未建立,系統會先呼叫 onCreate(),接著呼叫 onStartCommand();若服務已被建立,重複呼叫 startService() 不會重複建立服務,但會多次觸發 onStartCommand()。這種方式啟動的服務只能由 Context.stopService() 結束,結束時呼叫 onDestroy()。

5.2 bindService 方式

呼叫者與服務綁定在一起,呼叫者一旦退出,服務隨之終止,頗有「不求同時生,但求同時死」的意味。onBind() 只有在 bindService 時才會回呼,且即使多次呼叫 bindService(),該方法也只會被回呼一次。解除綁定用 unbindService(),服務結束時同樣會呼叫 onDestroy()。

官方給出的流程示意圖如下:

官方文件還說明:一個服務可以同時被 start 並 bind,此時系統會一直保持它運行(只要服務已 start,或設定了 BIND_AUTO_CREATE 標誌)。若兩個條件都不滿足,系統才會呼叫 onDestroy 終止服務——所有清理工作(終止線程、反註冊接收器)都應在 onDestroy 中完成。

六、服務的進程優先級

官方文件明確表示,Android 會盡量保持擁有服務的進程存活。當記憶體不足時,這類進程具有較高的優先級:

  1. 若服務正在執行 onCreate、onStartCommand 或 onDestroy,其所在進程會被提升為前台進程,避免被回收。
  2. 若服務已被 start,擁有它的進程優先級低於使用者可見的進程,但高於單純不可見的進程,因此一般不會被殺死。
  3. 若已有客戶端 bindService 連上,擁有服務的進程具有最高優先級,可視為可見。
  4. 若呼叫 startForeground(int, Notification) 把服務設為前台,系統會認為它對使用者可見,記憶體不足時不會被回收。

此外,若有其他組件(Service、Activity 等)運行在同一進程中,也會提高該進程的重要性。

七、兩種啟動方式的特點對照

7.1 startService

  • 第一次點擊按鈕啟動服務,會執行 onCreate 與 onStartCommand。
  • 第二次再按,只會再執行 onStartCommand。
  • 服務啟動後可以在設定頁面的「執行中」清單裡找到它。
  • 服務會長期在後台運行,直到使用者手動停止或呼叫 stopService 才會銷毀。

7.2 bindService

自訂服務類中的 onBind(),是在 Activity 執行 bindService() 綁定操作後被呼叫的。bindService() 需要傳入三個參數:

  1. Intent 物件,用於指定目標服務。
  2. ServiceConnection 物件,代表連線本身。執行 bindService() 後,服務與 Activity 之間的連結建立,此時回呼服務的 onBind(),它會回傳一個 IBinder 物件。我們可以在服務中自訂一個繼承 Binder 的中間人類別,把要對外開放的方法寫在裡面;接著 Activity 中的 onServiceConnected() 會被觸發,透過傳入的 IBinder 參數即可呼叫服務的方法。
  3. 標誌位,傳入 BIND_AUTO_CREATE 表示 Activity 與 Service 建立關聯後自動建立服務,這會觸發 onCreate(),但 onStartCommand() 不會執行。
// 服務中自定義的中間人物件
public class MyBinder extends Binder {
    public void startDownload() {
        // 具體下載邏輯
    }
}

// Activity 中建立連線的 ServiceConnection
private ServiceConnection connection = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName name) {}

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        myBinder = (MyService.MyBinder) service;
        myBinder.startDownload();
    }
};

bindService 的特點:

  • 第一次點擊啟動時,執行 onCreate 與 onBind。
  • 第二次再呼叫 bindService,服務不會再響應。
  • Activity 銷毀時服務也隨之銷毀——不求同時生,但求同時死。
  • 這種方式啟動的服務在設定頁面中找不到,相當於一個隱形服務。
  • bindService 不能重複解綁,重複呼叫 unbindService 會報錯。

八、進階用法:在服務中註冊特殊廣播

服務生命週期長,很適合承擔需要長期監聽的工作,例如螢幕的鎖屏與解鎖。

第一步,建立廣播接收者:

public class ScreenReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if ("android.intent.action.SCREEN_OFF".equals(action)) {
            System.out.println("說明螢幕鎖屏了");
        } else if ("android.intent.action.SCREEN_ON".equals(action)) {
            System.out.println("說明螢幕解鎖了");
        }
    }
}

第二步,建立服務,在 onCreate 中註冊、在 onDestroy 中反註冊:

public class ScreenService extends Service {

    private ScreenReceiver receiver;

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

    // 服務第一次啟動時呼叫
    @Override
    public void onCreate() {
        receiver = new ScreenReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.SCREEN_OFF");
        filter.addAction("android.intent.action.SCREEN_ON");
        registerReceiver(receiver, filter);
        super.onCreate();
    }

    // 服務銷毀時呼叫
    @Override
    public void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}

第三步,別忘了在 manifest 中註冊這個 service。

至於為什麼要引入 bindService?答案很單純:為了呼叫服務裡面的方法。startService 只能「下指令」,bindService 才能「拿回一個可以互相呼叫的通道」。

九、前台服務(Foreground Service)

Service 幾乎都在後台默默工作,但系統優先級偏低,記憶體吃緊時隨時可能被回收。如果希望服務能穩定存活,可以考慮前台 Service。

前台 Service 與普通 Service 最大的差別在於:它會在系統狀態欄保留一個持續運行中的圖示,下拉後還能看到更詳細的資訊,效果類似通知。實務上使用前台 Service 往往不只是為了防回收,有些產品需求本身也要求常駐提示——例如墨跡天氣,它在後台更新資料的同時,狀態欄會一直顯示當前天氣。

public class MyService extends Service {
    public static final String TAG = "MyService";
    private MyBinder mBinder = new MyBinder();

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

        Notification notification = new Notification(
                R.drawable.ic_launcher, "有通知到來",
                System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent =
                PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, "Title", "Message",
                pendingIntent);

        // 讓 MyService 變成前台 Service
        startForeground(1, notification);

        Log.d(TAG, "onCreate() executed");
    }
    // ...
}

做法不複雜:先建立 Notification 物件,呼叫 setLatestEventInfo() 初始化版面與資料(並設定點擊後開啟 MainActivity),然後呼叫 startForeground() 把服務提升為前台服務,通知圖示就會顯示出來。

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