Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Activity 與 Service 的綁定機制詳解

編輯:Android 開發實例

綁定能帶來什麼

當一個 Activity 綁定到某個 Service 上時,Activity 就持有了該 Service 實例的引用,可以直接調用正在運行的 Service 所暴露的方法。這與單純的 startService 不同:後者只下達一次意圖,前者建立的是一條可以雙向通信的通道。

Service 端:實現 onBind

綁定的基礎是 Service 提供一個 IBinder。通常的做法是定義一個繼承 Binder 的内部類,並在它的方法裡返回 Service 自身:

private final IBinder binder = new MyBinder();

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

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

Activity 端:建立連接

連接的過程由 ServiceConnection 承擔。實現這個接口並重寫兩個回調:連接建立時能拿到 Service 的引用,連接意外斷開時則把引用清空。

// Reference to the service
private MyService serviceBinder;

// Handles the connection between the service and activity
private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        // Called when the connection is made.
        serviceBinder = ((MyService.MyBinder) service).getService();
    }

    public void onServiceDisconnected(ComponentName className) {
        // Received when the service unexpectedly disconnects.
        serviceBinder = null;
    }
};

發起綁定

調用 bindService,傳入一個指向目標 Service 的 Intent(顯式或隱式均可)以及上面實現好的 ServiceConnection 實例。第三個參數通常用 Context.BIND_AUTO_CREATE,表示在沒有實例時自動創建:

@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    // Bind to the service
    Intent bindIntent = new Intent(MyActivity.this, MyService.class);
    bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
}

一旦 Service 對象就位,就能在 onServiceConnected 中透過 serviceBinder 訪問它的公共方法與屬性。

一點延伸

Android 應用的進程之間通常不共享內存,但在某些場景下,你的應用確實需要與跑在其他應用進程中的 Service 交互。此時可以借助 AIDL 生成跨進程的 Binder 存根,讓綁定關係跨越進程邊界——這也是系統服務能被各個應用調用的基礎。

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