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

Android AIDL跨進程通訊實戰:從原理到完整實例

編輯:關於 Android 程式設計

在我們的日常應用開發中,AIDL這項技術並不常被直接採用,但像新浪微博的SSO登入,其背後原理正是AIDL。本文將以一個完整的實例,深入講解AIDL的原理與實作方法。

AIDL(Android接口描述語言)是一種接口描述語言,編譯器能透過 aidl 檔生成一段程式碼,藉由預先定義的接口達到兩個進程內部通訊的目的。若需要在一個Activity中存取另一個Service裡的某個物件,就需要先將該物件轉化成AIDL可識別的參數,再透過AIDL傳遞,接收端則用這些參數重組出所需的物件。

說白了,AIDL就是定義一個接口,客戶端(呼叫端)透過 bindService 與遠端服務端建立連線,連線建立時會回傳一個 IBinder 物件(即服務端 Binder 的 BinderProxy)。客戶端透過 asInterface 函式將這個 BinderProxy 包裝成本地的 Proxy,並透過其中的 mRemote 欄位執行遠端方法呼叫。

一、AIDL接口聲明

在 src 目錄下建立 com.example.advanceandroid.aidl 套件,並在其中建立 ILogin.aidl 檔(注意是建立檔案而非類別)。在 ILogin.aidl 中聲明接口:

 package com.example.advanceandroid.aidl; interface ILogin { String login(); } 

請注意,接口與方法聲明都不需要(也不能)加上 public。若Eclipse開啟了自動編譯,會在 gen 目錄下生成對應的 ILogin.java 檔:

 package com.example.advanceandroid.aidl; public interface ILogin extends android.os.IInterface { /** Local-side IPC implementation stub class. */ public static abstract class Stub extends android.os.Binder implements com.example.advanceandroid.aidl.ILogin { private static final java.lang.String DESCRIPTOR = "com.example.advanceandroid.aidl.ILogin"; /** Construct the stub at attach it to the interface. */ public Stub() { this.attachInterface(this, DESCRIPTOR); } /** * Cast an IBinder object into an com.example.advanceandroid.aidl.ILogin * interface, generating a proxy if needed. */ public static com.example.advanceandroid.aidl.ILogin asInterface(android.os.IBinder obj) { if ((obj == null)) { return null; } android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); if (((iin != null) && (iin instanceof com.example.advanceandroid.aidl.ILogin))) { return ((com.example.advanceandroid.aidl.ILogin) iin); } return new com.example.advanceandroid.aidl.ILogin.Stub.Proxy(obj); } @Override public android.os.IBinder asBinder() { return this; } @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_login: { // 1、登錄請求,執行的是this.login(); data.enforceInterface(DESCRIPTOR); java.lang.String _result = this.login(); reply.writeNoException(); reply.writeString(_result); return true; } } return super.onTransact(code, data, reply, flags); } private static class Proxy implements com.example.advanceandroid.aidl.ILogin { private android.os.IBinder mRemote; Proxy(android.os.IBinder remote) { mRemote = remote; } @Override public android.os.IBinder asBinder() { return mRemote; } public java.lang.String getInterfaceDescriptor() { return DESCRIPTOR; } @Override public java.lang.String login() throws android.os.RemoteException // 2、Proxy中的login,通過Binder機制實現IPC { android.os.Parcel _data = android.os.Parcel.obtain(); android.os.Parcel _reply = android.os.Parcel.obtain(); java.lang.String _result; try { _data.writeInterfaceToken(DESCRIPTOR); mRemote.transact(Stub.TRANSACTION_login, _data, _reply, 0); _reply.readException(); _result = _reply.readString(); } finally { _reply.recycle(); _data.recycle(); } return _result; } } static final int TRANSACTION_login = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); } public java.lang.String login() throws android.os.RemoteException; } 

可以看到,自動生成的 Stub 類別繼承了 Binder 並實作了 ILogin 接口。其中最重要的是 asInterface() 函式:它會判斷傳入的 obj 是否為本地接口,若是則直接轉型,否則以 Proxy 內部類別包裝並賦值給 mRemote。而 Proxy 的 login() 函式(註解2)則透過 Binder 機制向服務端傳遞請求與資料。至此,客戶端的工作便完成了。

二、服務端AIDL接口

服務端需在相同套件下建立同名的 aidl 檔,可直接將客戶端的 ILogin.aidl 複製過去(若用到自定義型別,兩端都需具備)。此時服務端的 onTransact 函式(註解1)在接收到 TRANSACTION_login 請求時,會執行 this.login()。兩端就這樣透過 Binder 機制對接起來,類似 C/S 模式。

接著,最重要的一步是建立一個 Service:

 /** * AIDL服務端接口,LoginStubImpl實現了ILogin接口. * * @author mrsimple */ public class LoginService extends Service { /** * */ IBinder mBinder = new LoginStubImpl(); /** * @author mrsimple */ class LoginStubImpl extends Stub { @Override public String login() throws RemoteException { return "這是從 " + this.getClass().getName() + " 返回的字符串"; } } /* * 返回Binder實例,即實現了ILogin接口的Stub的子類,這裡為LoginStubImpl * @see android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { return mBinder; } } 

這個 LoginService 繼承自 Service,並建立一個繼承 Stub 的內部類 LoginStubImpl,實作 login() 方法。同時宣告一個 IBinder 欄位:

 IBinder mBinder = new LoginStubImpl();

並在 onBind 函式中回傳 mBinder。當客戶端建立連線時,會呼叫 onBind 回傳 mBinder,客戶端在 ServiceConnection 的 onServiceConnected 中取得的 IBinder,正是經過 BinderProxy 包裝後的 mBinder。

別忘了在 AndroidManifest.xml 中註冊 LoginService:

 <!-- aidl server service --> <service android:name="com.example.advanceandroid.aidl.LoginService" > <intent-filter> <action android:name="com.example.advanceandroid.aidl.LoginService" /> </intent-filter> </service> 

三、客戶端建立連線

在Activity中加入以下程式碼:

 ServiceConnection mLoginConnection = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { Log.d("", "### aidl disconnected."); } @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d("", "### aidl onServiceConnected. service : " + service.getClass().getName()); ILogin login = Stub.asInterface(service); Log.d("", "### after asInterface : " + login.getClass().getName()); try { Log.d("", "### login : " + login.login()); // Toast.makeText(MainActivity.this, "onServiceConnected : " + // login.login(), // Toast.LENGTH_SHORT).show(); } catch (RemoteException e) { e.printStackTrace(); } } }; @Override protected void onResume() { super.onResume(); // 服務端的action Intent aidlIntent = new Intent("com.example.advanceandroid.aidl.LoginService"); bindService(aidlIntent, mLoginConnection, Context.BIND_AUTO_CREATE); } @Override protected void onStop() { super.onStop(); // unbind unbindService(mLoginConnection); } 

四、運行結果

先運行服務端,再啟動客戶端,可以看到客戶端輸出如下Log:

 09-02 10:40:54.662: D/(9589): ### aidl onServiceConnected. service : android.os.BinderProxy 09-02 10:40:54.662: D/(9589): ### after asInterface : com.example.advanceandroid.aidl.ILogin$Stub$Proxy 09-02 10:40:54.662: D/(9589): ### login : 這是從 com.example.advanceandroid.aidl.LoginService$LoginStubImpl 返回的字符串 

可以看到,onServiceConnected 中的 service 物件是 BinderProxy 型別,經過 asInterface 轉換後被包裝成 Proxy 型別,但呼叫時執行的卻是服務端 LoginStubImpl 中的 login() 函式。這正是AIDL跨進程通訊的精妙之處:LoginStubImpl 的 mBinder 被服務端包裝成 BinderProxy,再經客戶端的 Proxy 包裝,透過 Binder 機制完成資料傳輸與IPC。

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