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

AIDL 與 Binder 框架淺析:從生成代碼看懂跨進程調用

編輯:Android 資訊

1、概述

Binder 能幹什麼?它提供系統中任何程序都能訪問的全局服務。這類能力任何系統都得有,下面我們快速看一下 Android 的 Binder 框架長什麼樣。

Android Binder 框架分為三部分:服務器接口、Binder 驅動、客戶端接口。道理很直白——要提供全局服務,服務提供方就是服務器接口,任意程序就是客戶端接口,兩者透過 Binder 驅動互相訪問。

服務器端接口:本質上是一個 Binder 類的對象。它一旦創建,內部就會啟動一個隱藏線程,接收 Binder 驅動送來的消息;收到後執行 Binder 對象的 onTransact() 函數,並依參數分派到不同的服務器端代碼。

Binder 驅動:同樣是 Binder 類的實例,客戶端透過它訪問遠程服務。

客戶端接口:取得 Binder 驅動,調用它的 transact() 把消息送向服務器。

如果上面的描述有點抽象,別擔心,下面的例子會把它講清楚。實踐是檢驗真理的唯一標準。

2、AIDL 的使用

對 Android 稍微熟一點的人應該都用過 AIDL。沒用過也無妨,我們直接用一個例子把它跑一遍。

接下來用 AIDL 實作一個跨進程的加減法調用。

1、服務端

新建一個項目,建立包名 com.zhy.calc.aidl,在包內新增 ICalcAIDL 文件:

package com.zhy.calc.aidl;

interface ICalcAIDL {
    int add(int x , int y);
    int min(int x , int y );
}

注意,文件名為 ICalcAIDL.aidl。

之後項目的 gen 目錄下會生成一個 ICalcAIDL.java,先不貼它的代碼,後面會詳細拆解。

接著在項目裡新建一個 Service:

package com.example.zhy_binder;

import com.zhy.calc.aidl.ICalcAIDL;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class CalcService extends Service {

    private static final String TAG = "server";

    public void onCreate() {
        Log.e(TAG, "onCreate");
    }

    public IBinder onBind(Intent t) {
        Log.e(TAG, "onBind");
        return mBinder;
    }

    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
    }

    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    public void onRebind(Intent intent) {
        Log.e(TAG, "onRebind");
        super.onRebind(intent);
    }

    private final ICalcAIDL.Stub mBinder = new ICalcAIDL.Stub() {
        @Override
        public int add(int x, int y) throws RemoteException {
            return x + y;
        }

        @Override
        public int min(int x, int y) throws RemoteException {
            return x - y;
        }
    };
}

在這個 Service 中,我們用生成的 ICalcAIDL 創建了 mBinder 對象,並在 onBind 裡返回它。

最後記得在 AndroidManifest 中註冊:

<service android:name="com.example.zhy_binder.CalcService" >
    <intent-filter>
        <action android:name="com.zhy.aidl.calc" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</service>

這裡我們指定了 action 名稱,因為稍後會在另一個應用中透過 Intent 來查找這個 Service。它不需要 Activity,所以我也沒寫;安裝完成後看不到圖標,就靜靜跑在後台。

服務端到此完成,下面寫客戶端。

2、客戶端

客戶端代碼比較簡單:一個含四個按鈕的布局,分別是綁定服務、解除綁定、調用加法、調用減法。

布局文件:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="bindService"
        android:text="BindService" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="unbindService"
        android:text="UnbindService" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="addInvoked"
        android:text="12+12" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="minInvoked"
        android:text="50-12" />
</LinearLayout>

主 Activity:

package com.example.zhy_binder_client;

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;
import android.view.View;
import android.widget.Toast;

import com.zhy.calc.aidl.ICalcAIDL;

public class MainActivity extends Activity {

    private ICalcAIDL mCalcAidl;

    private ServiceConnection mServiceConn = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("client", "onServiceDisconnected");
            mCalcAidl = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("client", "onServiceConnected");
            mCalcAidl = ICalcAIDL.Stub.asInterface(service);
        }
    };

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

    /**
     * 點擊 BindService 按鈕時調用
     */
    public void bindService(View view) {
        Intent intent = new Intent();
        intent.setAction("com.zhy.aidl.calc");
        bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE);
    }

    /**
     * 點擊 unBindService 按鈕時調用
     */
    public void unbindService(View view) {
        unbindService(mServiceConn);
    }

    /**
     * 點擊 12+12 按鈕時調用
     */
    public void addInvoked(View view) throws Exception {
        if (mCalcAidl != null) {
            int addRes = mCalcAidl.add(12, 12);
            Toast.makeText(this, addRes + "", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "服務器被異常殺死,請重新綁定服務端", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 點擊 50-12 按鈕時調用
     */
    public void minInvoked(View view) throws Exception {
        if (mCalcAidl != null) {
            int addRes = mCalcAidl.min(58, 12);
            Toast.makeText(this, addRes + "", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "服務端未綁定或被異常殺死,請重新綁定服務端", Toast.LENGTH_SHORT).show();
        }
    }
}

很標準的綁定服務代碼。

直接看運行結果:

先點擊 BindService,查看 log:

08-09 22:56:38.959: E/server(29692): onCreate
08-09 22:56:38.959: E/server(29692): onBind
08-09 22:56:38.959: E/client(29477): onServiceConnected

可以看到,點擊綁定之後,服務端執行了 onCreate 與 onBind,客戶端執行了 onServiceConnected,說明兩端已經打通。

然後點擊 12+12 與 50-12,都能正確調用服務端代碼並返回結果。

接著點擊 unBindService:

08-09 22:59:25.567: E/server(29692): onUnbind
08-09 22:59:25.567: E/server(29692): onDestroy

由於當前只有一個客戶端綁定了這個 Service,所以 onUnbind 與 onDestroy 被相繼調用。

有意思的是,此時繼續點擊 12+12 與 50-12,居然仍然能正確執行——也就是說 onUnbind 被調用並不代表連接立刻斷開。那到底什麼時候才會斷?答案是服務端被異常終止的時候。我們到「正在運行的程序」裡找到這個服務:

點擊停止,此時查看 log:

08-09 23:04:21.433: E/client(30146): onServiceDisconnected

onServiceDisconnected 被觸發,連接這才真正斷開。現在再點 12+12 或 50-12,就會彈出服務端斷開的 Toast 提示。

說了這麼多,好像還沒碰到 Binder 框架。接下來我們看看 AIDL 到底替我們做了什麼。

3、分析 AIDL 生成的代碼

1、服務端

服務端提供的服務是由下面這個對象執行的:

private final ICalcAIDL.Stub mBinder = new ICalcAIDL.Stub() {
    @Override
    public int add(int x, int y) throws RemoteException {
        return x + y;
    }

    @Override
    public int min(int x, int y) throws RemoteException {
        return x - y;
    }
};

來看看 Stub 這個類的聲明:

public static abstract class Stub extends android.os.Binder implements com.zhy.calc.aidl.ICalcAIDL

清清楚楚:它是 Binder 的子類,正好印證了開篇所說「服務端其實是一個 Binder 類的實例」。

接著看它的 onTransact():

@Override
public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags)
        throws android.os.RemoteException {
    switch (code) {
        case INTERFACE_TRANSACTION: {
            reply.writeString(DESCRIPTOR);
            return true;
        }
        case TRANSACTION_add: {
            data.enforceInterface(DESCRIPTOR);
            int _arg0;
            _arg0 = data.readInt();
            int _arg1;
            _arg1 = data.readInt();
            int _result = this.add(_arg0, _arg1);
            reply.writeNoException();
            reply.writeInt(_result);
            return true;
        }
        case TRANSACTION_min: {
            data.enforceInterface(DESCRIPTOR);
            int _arg0;
            _arg0 = data.readInt();
            int _arg1;
            _arg1 = data.readInt();
            int _result = this.min(_arg0, _arg1);
            reply.writeNoException();
            reply.writeInt(_result);
            return true;
        }
    }
    return super.onTransact(code, data, reply, flags);
}

開篇提過:服務端的 Binder 實例會依據客戶端透過 Binder 驅動送來的消息執行 onTransact,再由參數決定要跑哪段服務端代碼。

onTransact 有四個參數:code、data、reply、flags。

code 是一個整數唯一標識,用來區分要執行哪個方法,由客戶端傳入。

data 是客戶端傳過來的參數。

reply 是服務端要寫回去的返回值。

flags 標明是否雙向:0 為有返回值(雙向),1 為沒有(單向)。

仔細看 case TRANSACTION_min 裡的代碼:

data.enforceInterface(DESCRIPTOR);

它與客戶端的 writeInterfaceToken 相對應,用來標識遠程服務的名稱。

int _arg0;
_arg0 = data.readInt();
int _arg1;
_arg1 = data.readInt();

接著依次讀出客戶端傳入的兩個參數。

int _result = this.min(_arg0, _arg1);
reply.writeNoException();
reply.writeInt(_result);

然後執行 this.min,也就是我們自己實現的方法,結果透過 reply 寫回。add 的處理同理。

可見 AIDL 生成的 Stub 類,把服務端本來需要手寫的序列化、分派、回寫等代碼全包了。

2、客戶端

客戶端主要透過 ServiceConnection 與服務端建立連接:

private ServiceConnection mServiceConn = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName name) {
        Log.e("client", "onServiceDisconnected");
        mCalcAidl = null;
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.e("client", "onServiceConnected");
        mCalcAidl = ICalcAIDL.Stub.asInterface(service);
    }
};

如果你夠敏銳,應該已經猜到:onServiceConnected 裡那個 IBinder 實例,正是開篇所說的 Binder 驅動,同樣是一個 Binder 實例。

而 ICalcAIDL.Stub.asInterface 最終調用了:

return new com.zhy.calc.aidl.ICalcAIDL.Stub.Proxy(obj);

這個 Proxy 實例接收了我們的 Binder 驅動,並封裝了調用服務端的細節。開篇說過,客戶端會透過 Binder 驅動的 transact() 方法調用服務端代碼,直接看 Proxy 的 add 方法:

@Override
public int add(int x, int y) throws android.os.RemoteException {
    android.os.Parcel _data = android.os.Parcel.obtain();
    android.os.Parcel _reply = android.os.Parcel.obtain();
    int _result;
    try {
        _data.writeInterfaceToken(DESCRIPTOR);
        _data.writeInt(x);
        _data.writeInt(y);
        mRemote.transact(Stub.TRANSACTION_add, _data, _reply, 0);
        _reply.readException();
        _result = _reply.readInt();
    } finally {
        _reply.recycle();
        _data.recycle();
    }
    return _result;
}

先建立兩個 Parcel,一個傳數據,一個收結果。

_data.writeInterfaceToken(DESCRIPTOR) 與服務端的 enforceInterface 對應。

_data.writeInt(x)、_data.writeInt(y) 寫入要傳遞的參數。

mRemote.transact(Stub.TRANSACTION_add, _data, _reply, 0) 終於出現了我們的 transact:第一個參數對應服務端的 code,_data 與 _reply 分別對應 data 與 reply,最後的 0 表示雙向。

_reply.readException() 與 _result = _reply.readInt() 讀出服務端返回的數據並 return。可以看到它和服務端的 onTransact 幾乎是一行對一行。

至此,我們已經透過 AIDL 生成的代碼把 Android Binder 框架的工作原理講完了。Service 的作用,其實就是替我們創建 Binder 驅動,也就是服務端與客戶端之間的那座橋。

AIDL 做的事,是依據我們寫的 aidl 文件生成一個接口、一個供服務端使用的 Stub 類,以及一個供客戶端使用的 Proxy 類。那麼問題來了:我們能不能完全不寫 AIDL,也實現遠程通信?下面就用代碼證明可以。

4、不依賴 AIDL 實現進程間通訊

1、服務端代碼

新建一個 CalcPlusService.java,用來實現乘法與除法:

package com.example.zhy_binder;

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

public class CalcPlusService extends Service {

    private static final String DESCRIPTOR = "CalcPlusService";
    private static final String TAG = "CalcPlusService";

    public void onCreate() {
        Log.e(TAG, "onCreate");
    }

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

    public IBinder onBind(Intent t) {
        Log.e(TAG, "onBind");
        return mBinder;
    }

    public void onDestroy() {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
    }

    public boolean onUnbind(Intent intent) {
        Log.e(TAG, "onUnbind");
        return super.onUnbind(intent);
    }

    public void onRebind(Intent intent) {
        Log.e(TAG, "onRebind");
        super.onRebind(intent);
    }

    private MyBinder mBinder = new MyBinder();

    private class MyBinder extends Binder {
        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
                throws RemoteException {
            switch (code) {
                case 0x110: {
                    data.enforceInterface(DESCRIPTOR);
                    int _arg0;
                    _arg0 = data.readInt();
                    int _arg1;
                    _arg1 = data.readInt();
                    int _result = _arg0 * _arg1;
                    reply.writeNoException();
                    reply.writeInt(_result);
                    return true;
                }
                case 0x111: {
                    data.enforceInterface(DESCRIPTOR);
                    int _arg0;
                    _arg0 = data.readInt();
                    int _arg1;
                    _arg1 = data.readInt();
                    int _result = _arg0 / _arg1;
                    reply.writeNoException();
                    reply.writeInt(_result);
                    return true;
                }
            }
            return super.onTransact(code, data, reply, flags);
        }
    }
}

這回服務端完全自己來:自定義一個 Binder 子類,復寫 onTransact。我們約定服務標識為 CalcPlusService,0x110 代表乘法,0x111 代表除法。

記得在 AndroidManifest 中註冊:

<service android:name="com.example.zhy_binder.CalcPlusService" >
    <intent-filter>
        <action android:name="com.zhy.aidl.calcplus" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</service>

服務端結束。

2、客戶端代碼

單獨新建一個項目,代碼和上一例很類似。先看布局:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="bindService"
        android:text="BindService" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="unbindService"
        android:text="UnbindService" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="mulInvoked"
        android:text="50*12" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="divInvoked"
        android:text="36/12" />
</LinearLayout>

按鈕換成了乘法和除法。

接著是 Activity:

package com.example.zhy_binder_client03;

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.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends Activity {

    private IBinder mPlusBinder;

    private ServiceConnection mServiceConnPlus = new ServiceConnection() {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("client", "mServiceConnPlus onServiceDisconnected");
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("client", " mServiceConnPlus onServiceConnected");
            mPlusBinder = service;
        }
    };

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

    public void bindService(View view) {
        Intent intentPlus = new Intent();
        intentPlus.setAction("com.zhy.aidl.calcplus");
        boolean plus = bindService(intentPlus, mServiceConnPlus, Context.BIND_AUTO_CREATE);
        Log.e("plus", plus + "");
    }

    public void unbindService(View view) {
        unbindService(mServiceConnPlus);
    }

    public void mulInvoked(View view) {
        if (mPlusBinder == null) {
            Toast.makeText(this, "未連接服務端或服務端被異常殺死", Toast.LENGTH_SHORT).show();
        } else {
            android.os.Parcel _data = android.os.Parcel.obtain();
            android.os.Parcel _reply = android.os.Parcel.obtain();
            int _result;
            try {
                _data.writeInterfaceToken("CalcPlusService");
                _data.writeInt(50);
                _data.writeInt(12);
                mPlusBinder.transact(0x110, _data, _reply, 0);
                _reply.readException();
                _result = _reply.readInt();
                Toast.makeText(this, _result + "", Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
                e.printStackTrace();
            } finally {
                _reply.recycle();
                _data.recycle();
            }
        }
    }

    public void divInvoked(View view) {
        if (mPlusBinder == null) {
            Toast.makeText(this, "未連接服務端或服務端被異常殺死", Toast.LENGTH_SHORT).show();
        } else {
            android.os.Parcel _data = android.os.Parcel.obtain();
            android.os.Parcel _reply = android.os.Parcel.obtain();
            int _result;
            try {
                _data.writeInterfaceToken("CalcPlusService");
                _data.writeInt(36);
                _data.writeInt(12);
                mPlusBinder.transact(0x111, _data, _reply, 0);
                _reply.readException();
                _result = _reply.readInt();
                Toast.makeText(this, _result + "", Toast.LENGTH_SHORT).show();
            } catch (RemoteException e) {
                e.printStackTrace();
            } finally {
                _reply.recycle();
                _data.recycle();
            }
        }
    }
}

為了讓對應關係一目了然,我直接把代碼寫在 mulInvoked 裡,兩端都沒有額外抽象接口。綁定服務時,透過 onServiceConnected 拿到 Binder 驅動 mPlusBinder;然後準備數據、調用 transact,用 code 指定服務端要跑哪個分支,其餘邏輯和前面拆解的生成代碼完全一致。

運行結果:

兩個應用程序的通訊就這麼實現了,全程沒有任何 aidl 文件——這也從側面驗證了我們前面的分析是正確的。

就到這裡。相信看完這篇,你對 AIDL 與 Binder 的理解會更紮實一層。

測試代碼:先安裝 server 端,再安裝 client 端。

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