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

Android 四大天王之 Service:兩種啟動方式、生命週期與完整範例

編輯:關於 Android 程式設計

如果說 Activity 是站在使用者眼前的「前台」,那 Service 就是默默在幕後運作的「後台」。它沒有使用者介面,不容易被察覺,卻是監控類、下載類、播放類應用的骨幹。使用方式和 Activity 一樣,都是透過 Intent 來調度。

一、建立一個 Service

第一步是繼承系統的 Service 類別:

public class CustomService extends Service { ... }

第二步別忘了到 AndroidManifest.xml 的 <application> 標籤底下註冊,否則執行期會找不到元件:

<service android:name=".MyService" />

二、兩種啟動方式,行為完全不同

Service 不會自己跑起來,必須由 Context.startService() 或 Context.bindService() 觸發。這兩個方法看起來相似,實際語意差很多。

1. startService():叫了就走,兩不相欠

當服務尚未建立時,系統會先呼叫 onCreate(),接著呼叫 onStartCommand(...)。若服務早已存在,重複呼叫 startService() 不會重複建立服務,但 onStartCommand(...) 會被呼叫多次。

這種方式啟動的服務,只能靠 stopService() 結束,結束時觸發 onDestroy()。最關鍵的一點是:呼叫者與服務之間沒有羈絆,即使呼叫者退出,服務仍然繼續運行。音樂播放器、檔案下載就屬於這類。

2. bindService():綁在一起,一榮俱榮

服務未建立時,一樣先走 onCreate(),接著走 onBind()。此時呼叫者與服務被綁定,呼叫者一旦退出,系統會先呼叫 onUnbind(),再呼叫 onDestroy()。若服務已處於綁定狀態,重複呼叫 bindService() 不會導致重複建立或重複綁定(也就是 onCreate() 與 onBind() 不會被多次觸發)。想主動解除,呼叫 unbindService() 即可,效果同樣是 onUnbind() → onDestroy()。

一句話總結:startService 是「你去忙你的」,bindService 是「咱們綁一起」。

三、Service 的生命週期

官方沒有為 Service 畫示意圖,於是照 Activity 的樣子補了一張:

從流程圖可以歸納出兩條路徑:

1. startService() 啟動:
startService() ▸ onCreate() ▸ onStartCommand() ▸ stopService() ▸ onDestroy()
 多次呼叫 startService() 不會重複建立服務,但 onStartCommand() 會被呼叫多次。

2. bindService() 啟動:
bindService() ▸ onCreate() ▸ onBind() ▸ unbindService() ▸ onUnbind() ▸ onDestroy()
 已綁定狀態下重複呼叫 bindService(),onBind() 不會被再次觸發。

四、完整案例

AndroidManifest.xml

<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="cn.lynn.service"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService" />
    </application>

</manifest>

strings.xml

<resources>
    <string name="app_name">Android四大天王之Service</string>
</resources>

main.xml:五顆按鈕把兩條路徑都走一遍

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button android:id="@+id/btnStartMyService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="StartMyService" />

    <Button android:id="@+id/btnStopMyService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="StopMyService" />

    <Button android:id="@+id/btnBindMyService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BindMyService" />

    <Button android:id="@+id/btnUnbindMyService"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="UnbindMyService" />

    <Button android:id="@+id/btnExitActivity"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ExitActivity" />

</LinearLayout>

MainActivity.java

package cn.lynn.service;

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 MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    Button mBtnStartMyService;
    Button mBtnStopMyService;
    Button mBtnBindMyService;
    Button mBtnUnbindMyService;
    Button mBtnExitActivity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mBtnStartMyService = (Button) findViewById(R.id.btnStartMyService);
        mBtnStartMyService.setOnClickListener(new MyOnClickListener());

        mBtnStopMyService = (Button) findViewById(R.id.btnStopMyService);
        mBtnStopMyService.setOnClickListener(new MyOnClickListener());

        mBtnBindMyService = (Button) findViewById(R.id.btnBindMyService);
        mBtnBindMyService.setOnClickListener(new MyOnClickListener());

        mBtnUnbindMyService = (Button) findViewById(R.id.btnUnbindMyService);
        mBtnUnbindMyService.setOnClickListener(new MyOnClickListener());

        mBtnExitActivity = (Button) findViewById(R.id.btnExitActivity);
        mBtnExitActivity.setOnClickListener(new MyOnClickListener());
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) { }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) { }
    };

    class MyOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, MyService.class);
            switch (v.getId()) {
                case R.id.btnStartMyService:
                    MainActivity.this.startService(intent);
                    break;
                case R.id.btnStopMyService:
                    MainActivity.this.stopService(intent);
                    break;
                case R.id.btnBindMyService:
                    MainActivity.this.bindService(intent, conn, Service.BIND_AUTO_CREATE);
                    break;
                case R.id.btnUnbindMyService:
                    if (MyService.ServiceState.equals("onBind")) {
                        MainActivity.this.unbindService(conn);
                    }
                    break;
                case R.id.btnExitActivity:
                    MainActivity.this.finish();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestory");
    }
}

MyService.java:用一個變數記錄自己走到哪一步

package cn.lynn.service;

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

public class MyService extends Service {
    private static final String TAG = "MyService";
    /** 記錄 Service 生命週期的各個狀態 */
    public static String ServiceState = "";

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind");
        ServiceState = "onBind";
        return null;
    }

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

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        ServiceState = "onStartCommand";
        return super.onStartCommand(intent, flags, startId);
    }

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

五、實際跑出來的樣子

App 畫面上就是上面那五顆按鈕:

點擊「StartMyService」,執行 startService(...),LogCat 輸出如下:

點擊「StopMyService」,執行 stopService(...),LogCat 輸出如下:

點擊「BindMyService」,執行 bindService(...),LogCat 輸出如下:

點擊「UnBindMyService」,執行 unbindService(...),LogCat 輸出如下:

把這幾張 log 對照前面的生命週期圖來看,哪個方法觸發了哪個 callback 一目了然。理解這個順序之後,再往上疊加通知列、前台服務(foreground service)這類進階用法,思路就會清楚很多。

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