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

Android 進階系列(五):Service 的兩種啟動方式與生命週期全解

編輯:關於 Android 開發

上一篇我們談完了 Activity 與 Intent,這次換 Service 登場。若把 Activity 比喻成使用者看得見的「前台」,那麼 Service 就是默默在幕後運作的「後台」——它沒有使用者介面,整個生命週期都在背景執行,特別適合承接音樂播放、檔案下載、資料同步這類不該被畫面綁住的工作。

Service 同樣由 Intent 啟動

這一點和 Activity 完全一致:Service 也是靠 Intent 來呼叫。要在專案裡新增一個 Service,需要兩個步驟。先寫一個繼承 android.app.Service 的類別,把實際要跑的邏輯放進去;接著打開 AndroidManifest.xml,在 Application → Application Nodes 中的 Service 標籤裡把它登記出來。少了第二步,系統根本認不出這個元件。

而從 Activity 這邊要啟動它,有兩個入口:startService() 與 bindService(),參數一樣用 Intent 傳遞。先看一下本文程式的執行結果:

兩條路徑,兩套生命週期

本文的示範重點有兩個:Service 的呼叫方式,以及它在不同情境下的狀態變化。下面這張圖呈現的是 startService() 之後再呼叫 stopService() 時,Service 所經歷的狀態推移:

而這張則是 bindService() 之後再 unbindService() 的狀態變化:

那麼,兩者差在哪裡?

關鍵差異在於「Service 的生命週期由誰掌控」:

  • startService 啟動的 Service:必須由 stopService() 收尾。若忘了呼叫,就會出現 Activity 已經關閉、Service 卻還在背景跑的情況,白白消耗資源。
  • bindService 啟動的 Service:可以透過 unbindService() 結束,也可以在 Activity 走到 onDestroy() 時自動解除綁定並隨之結束。

下面兩張圖把這個差異說得更清楚。第一張是 startService() 之後直接 Activity.finish() 的狀態變化,可以注意到 Service 依然在跑:

第二張則是 bindService() 之後 Activity.finish() 的狀態變化,Service 最後會自動完成 unbind:

實務上的判斷很簡單:需要長期在背景待命、不依賴任何頁面的工作(例如播放器中斷控制),用 startService;只是需要與某個 Activity 進行雙向溝通、頁面關掉就該收工的工作,用 bindService。

main.xml 版面配置

五顆按鈕分別對應啟動、停止、綁定、解綁與退出:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/btnStartMyService"
            android:text="StartMyService">
    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/btnStopMyService"
            android:text="StopMyService">
    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/btnBindMyService"
            android:text="BindMyService">
    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/btnUnbindMyService"
            android:text="UnbindMyService">
    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:id="@+id/btnExit"
            android:text="退出程式">

testService.java:Activity 端的呼叫

package com.testService;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
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.widget.Button;

public class testService extends Activity {
    Button btnStartMyService, btnStopMyService, btnBindMyService, btnUnbindMyService, btnExit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnStartMyService = (Button) this.findViewById(R.id.btnStartMyService);
        btnStartMyService.setOnClickListener(new ClickEvent());

        btnStopMyService = (Button) this.findViewById(R.id.btnStopMyService);
        btnStopMyService.setOnClickListener(new ClickEvent());

        btnBindMyService = (Button) this.findViewById(R.id.btnBindMyService);
        btnBindMyService.setOnClickListener(new ClickEvent());

        btnUnbindMyService = (Button) this.findViewById(R.id.btnUnbindMyService);
        btnUnbindMyService.setOnClickListener(new ClickEvent());

        btnExit = (Button) this.findViewById(R.id.btnExit);
        btnExit.setOnClickListener(new ClickEvent());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("Activity", "onDestroy");
    }

    private ServiceConnection _connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName arg0, IBinder arg1) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
        }
    };

    class ClickEvent implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(testService.this, MyService.class);
            if (v == btnStartMyService) {
                testService.this.startService(intent);
            }
            else if (v == btnStopMyService) {
                testService.this.stopService(intent);
            }
            else if (v == btnBindMyService) {
                testService.this.bindService(intent, _connection, Service.BIND_AUTO_CREATE);
            }
            else if (v == btnUnbindMyService) {
                if (MyService.ServiceState == "onBind")   // Service 綁定之後才能解綁
                    testService.this.unbindService(_connection);
            }
            else if (v == btnExit) {
                testService.this.finish();
            }
        }
    }
}

MyService.java:Service 端的狀態記錄

這裡刻意把每個回呼觸發時的狀態寫進一個靜態變數 ServiceState,方便外部按鈕判斷目前是否可以解綁,同時也能搭配 Logcat 觀察整條生命週期:

package com.testService;

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

public class MyService extends Service {
    static public String ServiceState = "";

    @Override
    public IBinder onBind(Intent arg0) {
        Log.e("Service", "onBind");
        ServiceState = "onBind";
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        super.onUnbind(intent);
        Log.e("Service", "onUnbind");
        ServiceState = "onUnbind";
        return false;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("Service", "onCreate");
        ServiceState = "onCreate";
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e("Service", "onDestroy");
        ServiceState = "onDestroy";
    }

    @Override
    public void onStart(Intent intent, int startid) {
        super.onStart(intent, startid);
        Log.e("Service", "onStart");
        ServiceState = "onStart";
    }
}

把這三段代碼跑起來,反覆點擊按鈕並搭配 Logcat 觀察,你會很直觀地感受到:Service 的「生死」取決於你怎麼啟動它。這也是為什麼在設計背景任務時,第一步永遠是先想清楚——這個服務該由誰來結束。

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