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

Android Service 全解析(二):bindService 綁定式服務與 Binder 通信

編輯:關於 Android 程式設計

startService() 只能單向派發指令,服務與使用者之間沒有來回通道。若需要讓 Activity 直接呼叫服務裡的方法並取得返回值,就必須改用 bindService()。本文示範一個本地服務(服務與存取者在同一進程)的完整實作。

核心目標

客戶端要做的其實只有一件事:拿到服務回傳的 Binder 物件,再用它呼叫服務中的方法。所有複雜度都在「如何拿到」這一步。

服務端:三步驟

首先自訂類別繼承 Service;接著寫一個內部類,同時繼承 Binder 並實作業務介面;最後複寫 onBind(),把該內部類的實例回傳。

這裡之所以要額外定義一個介面,是因為 Binder 內部類通常是私有成員,客戶端無法直接 new 出來接收;用介面當作共同的契約,既解決了可見性問題,也把業務邏輯抽象出來,是更規範的設計。

package cc.testservice2;

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

public class ServiceSubclass extends Service {
    private String[] names = new String[]{"小明", "小王", "小楊", "小李", "小強"};

    BinderSubclass mBinderSubclass = new BinderSubclass();

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

    // BinderSubclass 同時繼承 Binder 並實作業務介面
    private final class BinderSubclass extends Binder implements QueryInterface {
        public String queryByNumber(int number) {
            return query(number);
        }
    }

    // 服務內部的實際邏輯
    public String query(int i) {
        if (i > 0 && i < 6) {
            return names[i - 1];
        }
        return "查詢錯誤,請再次輸入";
    }
}

業務介面本身非常單純:

package cc.testservice2;

public interface QueryInterface {
    public String queryByNumber(int number);
}

客戶端:四步驟

寫一個類別實作 ServiceConnection 介面;建立它的實例;呼叫 bindService() 與服務建立連線;在 onServiceConnected() 回呼中接收 Binder 物件並轉型成業務介面。

package cc.testservice2;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView mNumberTextView;
    TextView mResultTextView;
    Button mSearchButton;
    ServiceConnectionImpl mServiceConnectionImpl;
    QueryInterface mBinder;

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

        // 用於接收服務返回的 Binder 物件
        mServiceConnectionImpl = new ServiceConnectionImpl();
        mNumberTextView = (TextView) findViewById(R.id.numberEditText);
        mResultTextView = (TextView) findViewById(R.id.resultTextView);
        mSearchButton = (Button) findViewById(R.id.searchButton);
        mSearchButton.setOnClickListener(new ButtonOnClickListener());

        Intent intent = new Intent(this, ServiceSubclass.class);
        // Activity 啟動時就建立與服務的連接
        bindService(intent, mServiceConnectionImpl, this.BIND_AUTO_CREATE);
    }

    private class ButtonOnClickListener implements OnClickListener {
        public void onClick(View v) {
            String number = mNumberTextView.getText().toString();
            String result = mBinder.queryByNumber(Integer.valueOf(number));
            mResultTextView.setText(result);
        }
    }

    private final class ServiceConnectionImpl implements ServiceConnection {
        // 綁定成功時回呼
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBinder = (QueryInterface) service;
        }

        // 解除綁定時回呼
        public void onServiceDisconnected(ComponentName name) {
            mBinder = null;
        }
    }

    @Override
    protected void onDestroy() {
        unbindService(mServiceConnectionImpl);
        super.onDestroy();
    }
}

佈局

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="請輸入1到5的數字" />

    <EditText
        android:id="@+id/numberEditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/searchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="查詢" />

    <TextView
        android:id="@+id/resultTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

四個必須注意的重點

綁定與解綁必須成對。兩者用的都是同一個 ServiceConnection 實例,漏掉 unbindService() 會造成連線洩漏。

一定要複寫 onDestroy()。只在 onCreate() 建立連線卻不在 Activity 銷毀時關閉,是新手最常犯的錯誤。

onServiceConnected() 是回呼,不是同步返回。它不是呼叫 bindService() 之後立刻觸發,而是等到系統完成綁定才呼叫。因此在該回呼被執行之前,mBinder 仍是 null,若使用者手快在此刻點擊按鈕就會崩潰,實務上應加上空值判斷或先禁用按鈕。

本地服務可以直接轉型。因為 Binder 內部類本身就實作了業務介面,客戶端可直接向下轉型;但這招只在同進程有效,跨進程時收到的會是代理物件,必須改用 AIDL 的 Stub.asInterface()。

bindService 的第三個參數

BIND_AUTO_CREATE 表示在沒有其他綁定時自動建立服務,這是最常用的旗標。另有 BIND_IMPORTANT、BIND_NOT_FOREGROUND 等,可用位元運算組合。多個客戶端可同時綁定同一個服務,系統會以第一個綁定建立它,並在最後一個解綁時銷毀它——這與 startService() 的生命週期規則完全不同,設計時別混淆。

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