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

深入解析 Android 的 startService 與 bindService

編輯:關於 Android 程式設計

什麼是 Service?

Service 是 Android 系統中的服務元件,有幾個鮮明的特點:它無法與使用者直接互動,必須由使用者或其他程式明確啟動;它的優先級相對較高——雖略低於前台應用,卻高於一般背景應用,因此當系統因記憶體不足而回收資源時,Service 被銷毀的機率相對較小。

什麼時候需要用到 Service?

Service 運行於背景,對使用者來說並非關注的焦點。舉個例子:當你開啟音樂播放後想去瀏覽圖片,又不希望音樂中斷,這時就需要 Service;又或者點開一個下載連結,你並不想盯著它下載完才去做別的事,而是希望手機一邊在背景下載、一邊還能讓你翻看新聞,這同樣是 Service 的典型場景。

Service 的分類

一般把 Service 分為兩類:本地 Service 與遠端 Service。

本地 Service 顧名思義,就是與當前應用位於同一個進程中的 Service,彼此共享同一塊記憶體區域,因此資料共享特別方便簡單。

遠端 Service 則涉及不同進程間的 Service 存取。由於 Android 出於系統安全考量,不同進程之間無法用一般方式共享資料,為此 Android 提供了 AIDL(Android Interface Definition Language,Android 介面描述語言)這個工具,後文會詳細介紹。

Service 的生命週期

與 Activity 相比,Service 的生命週期單純許多,只有 onCreate()、onStart()、onDestroy() 三個方法。

Activity 中與 Service 相關的方法:

startService(Intent intent):啟動一個 Service。

stopService(Intent intent):停止一個 Service。

如果想使用 Service 中的資料或呼叫其中的方法,則要透過以下方法:

public boolean bindService(Intent intent, ServiceConnection conn, int flags);

public void unbindService(ServiceConnection conn);

其中 intent 是導向 Service 的意圖,例如 Intent intent = new Intent(); intent.setClass(this, MyService.class);;conn 則是代表與 Service 連線狀態的類,當連線成功或失敗時,會主動觸發其內部的 onServiceConnected 或 onServiceDisconnected 方法。若想在 onServiceConnected() 中取得 Service 的資料,就在這裡實作即可。

使用 Service 的步驟

第一步:繼承 Service 類,實作自己的 Service。若想存取 Service 中的某些值,通常會提供一個繼承自 Binder 的內部類,透過 onBind() 方法回傳給請求方,這裡巧妙地利用了內部類能存取外部類屬性的特性。

第二步:在 AndroidManifest.xml 中註冊該 Service。

第三步:在 Activity 中進行啟動、綁定、解綁或停止 Service 的操作。

坊間常說「Service 不能與使用者互動」,其實這個說法並不嚴謹——我們完全可以透過 Activity 與 Service 互動。更精確的說法應該是:Service 不能與使用者進行「直接」互動。


bindService 介紹

bindService 用於綁定 Service,執行 Service 中的邏輯流程。

Service 透過 Context.startService() 啟動,透過 Context.stopService() 停止,也可以呼叫 Service.stopSelf() 或 Service.stopSelfResult() 讓自己停止。只要呼叫一次 stopService(),無論之前啟動了多少次,服務都會被停止。

客戶端也可以建立一個與 Service 的連線,並透過這個連線與 Service 溝通:用 Context.bindService() 綁定服務,用 Context.unbindService() 解除綁定。多個客戶端可以綁定同一個服務,而如果 Service 尚未啟動,bindService() 也能順帶把它啟動起來。

startService() 與 bindService() 這兩種模式並非完全獨立。你可以綁定一個已由 startService() 啟動的服務。例如一個背景播放音樂的服務透過 startService() 開始播放,當使用者想查看歌曲資訊時,Activity 可以呼叫 bindService() 與 Service 建立連線;這種情況下,stopService() 其實不會立刻停止服務,而是等到最後一次綁定解除後才真正結束。

bindService 啟動流程

context.bindService() → onCreate() → onBind() → Service running → onUnbind() → onDestroy() → Service stop

onBind() 會回傳給客戶端一個 IBind 介面實例,允許客戶端回呼服務的方法,例如取得 Service 實例、執行狀態或其他操作。此時呼叫者(如 Activity)便與 Service 綁定在一起,當呼叫者退出時,Service 會依序呼叫 onUnbind 與 onDestroy 相應退出。

因此 bindService 的生命週期為:onCreate → onBind(只呼叫一次,不可重複綁定)→ onUnbind → onDestroy。在 Service 每一次開啟與關閉的過程中,只有 onStart 可被多次呼叫(透過多次 startService),其他的 onCreate、onBind、onUnbind、onDestroy 在同一個生命週期中都只會被呼叫一次。

bindService 生命週期

像 Activity 一樣,Service 也有幾個用來改變狀態的生命週期方法,但數量更少,主要的三個是:void onCreate()、void onStart(Intent intent)、void onDestroy()。

透過實作這三個方法,你可以監聽 Service 的兩個嵌套循環:

1、整個生命週期:位於 onCreate() 與 onDestroy() 之間。與 Activity 相同,在 onCreate() 中初始化,在 onDestroy() 中釋放資源。例如背景音樂服務可以在 onCreate() 開始播放、在 onDestroy() 停止。

2、活動生命週期:始於 onStart(),這個方法會處理透過 startService() 傳入的 Intent。音樂服務可以藉由 Intent 找到要播放的音樂並開始背景播放。注意:Service 停止時沒有對應的回呼方法,也就是說沒有 onStop(),只有 onDestroy()。

onCreate() 與 onDestroy() 對所有 Service 都適用,無論是透過 startService() 還是 bindService() 啟動。然而,只有透過 startService() 啟動時才會呼叫 onStart()。若 Service 允許被綁定,還需實作 onBind()、onUnbind()、onRebind() 等額外方法。特別提醒:任何服務無論如何建立,預設客戶端都能連線,因此任何 Service 都能接收 onBind() 與 onUnbind()。

startService 與 bindService 範例

(1)MainActivity

public class MainActivity extends Activity {
    Button startServiceButton;      // 啟動服務按鈕
    Button shutDownServiceButton;   // 關閉服務按鈕
    Button startBindServiceButton;  // 啟動綁定服務按鈕

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWidget();
        regiestListener();
    }

    public void getWidget() {
        startServiceButton = (Button) findViewById(R.id.startServerButton);
        startBindServiceButton = (Button) findViewById(R.id.startBindServerButton);
        shutDownServiceButton = (Button) findViewById(R.id.sutdownServerButton);
    }

    public void regiestListener() {
        startServiceButton.setOnClickListener(startService);
        shutDownServiceButton.setOnClickListener(shutdownService);
        startBindServiceButton.setOnClickListener(startBinderService);
    }

    public Button.OnClickListener startService = new Button.OnClickListener() {
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, CountService.class);
            startService(intent);
            Log.v("MainStadyServics", "start Service");
        }
    };

    public Button.OnClickListener shutdownService = new Button.OnClickListener() {
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, CountService.class);
            stopService(intent);
            Log.v("MainStadyServics", "shutDown serveice");
        }
    };

    public Button.OnClickListener startBinderService = new Button.OnClickListener() {
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, UseBrider.class);
            startActivity(intent);
            Log.v("MainStadyServics", "start Binder Service");
        }
    };
}

(2)Service

package com.example.testservice;

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

public class CountService extends Service {
    boolean threadDisable;
    int count;

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

    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {
            public void run() {
                while (!threadDisable) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) { }
                    count++;
                    Log.v("CountService", "Count is" + count);
                }
            }
        }).start();
    }

    public void onDestroy() {
        super.onDestroy();
        this.threadDisable = true;
    }

    public int getConunt() {
        return count;
    }

    class ServiceBinder extends Binder {
        public CountService getService() {
            return CountService.this;
        }
    }
}

(3)bindService(記得這裡要取得並保存連結的物件)

package com.example.testservice;

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;

public class UseBrider extends Activity {
    CountService countService;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new UseBriderFace(this));
        Intent intent = new Intent(UseBrider.this, CountService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection conn = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder service) {
            countService = ((CountService.ServiceBinder) service).getService();
        }

        public void onServiceDisconnected(ComponentName name) {
            countService = null;
        }
    };

    protected void onDestroy() {
        super.onDestroy();
        this.unbindService(conn);
        Log.v("MainStadyServics", "out");
    }
}

注意:有時會遇到 onServiceConnected 不被呼叫的情況。基本上呼叫 bindService 後就會回呼 onServiceConnected,並在其中傳入一個 IBinder 實例供 Activity 保存。Service 中需建立一個實作 IBinder 的內部類,並在 onBind() 中回傳該實例,否則 onServiceConnected 不會被觸發。

兩種模式的適用場景

1、透過 startService 開啟的服務:一旦啟動,服務與呼叫者之間就不再有任何關聯,呼叫者無法存取 Service 內的方法;即使呼叫者被系統回收或呼叫了 onDestroy,Service 仍會繼續存在。

2、透過 bindService 開啟的服務:啟動後呼叫者與服務之間仍存在聯繫,一旦呼叫者銷毀,Service 也會跟著結束。

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