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

Android 本地服務與 Activity 雙向通訊:Binder 綁定的實作

編輯:關於 Android 程式設計

Service 有兩種啟動方式:startService 是「下指令」,彼此不往來;bindService 則是「建立通道」,讓 Activity 能直接呼叫 Service 的公開方法。若你的服務需要回傳資料給介面,就該用後者。本文以 Binder 機制實作一個可被 Activity 呼叫的本地服務。

一、定義介面

先抽出一個介面,讓 Activity 與 Service 都依賴它,避免邏輯散落在兩處:

package cn.itcast.service;

public interface IService {
    public String getName(int id);
}

二、Service 端

package cn.itcast.service;

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

public class MyService extends Service {
    private Binder binder = new MyBinder();

    public String getName(int id) {
        return "傳智播客";
    }

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

    private final class MyBinder extends Binder implements IService {
        public String getName(int id) {
            return MyService.this.getName(23);
        }
    }
}

三個重點:

  • onBind() 回傳的就是 Activity 端會拿到的那個物件,它是兩邊溝通的橋樑。
  • MyBinder 是內部類別,因此能直接存取外部 Service 的成員;寫成 MyService.this.getName() 是為了避免與自身的同名方法混淆。
  • 內部類別持有外部 Service 的隱含參考,Service 被銷毀時若 Binder 仍被 Activity 持有,記憶體無法釋放。範例為求簡潔未處理,實 project 應留意生命週期。

三、Activity 端

package cn.itcast.service;

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.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
    private MyServiceConnection conn;
    private IService myservice;

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

        conn = new MyServiceConnection();
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);

        Button button = (Button) this.findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TextView resultView = (TextView) findViewById(R.id.result);
                resultView.setText(myservice.getName(56));
            }
        });
    }

    private final class MyServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myservice = (IService) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            myservice = null;
        }
    }

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

流程是:呼叫 bindService() 並傳入 ServiceConnection → 系統建立連線後回呼 onServiceConnected(),把 Binder 交給我們 → 轉型成 IService 之後即可直接呼叫其方法。

BIND_AUTO_CREATE 的意義是:若服務尚未存在就順便建立它。這也是 bindService 與 startService 最大的行為差異。

四、千萬別忘記 unbindService

綁定必須成對解除。若在 onDestroy 中沒有呼叫 unbindService(conn),系統會拋出 ServiceConnection leaked 的例外。此外,只要還有一個 client 綁著,Service 就不會被回收;全部解除後才會銷毀。

五、manifest 註冊

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

    <application android:icon="@drawable/icon" 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>

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

本地服務(同一 App 內使用)不需要 intent-filter,只要用 <service> 註冊即可。

六、這種寫法的邊界

上述 Binder 機制只在「同一支 App」內有效——Service 與 Activity 位於同一進程, binder 物件直接傳遞,沒有跨進程序列化的問題。若要跨 App 提供服務,就必須改用 AIDL:定義 .aidl 檔,讓工具產生 Parcelable 的序列化與代理程式碼。判斷標準很簡單:服務只給自己用,用 Binder 就好;要給別人用,才需要 AIDL。

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