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

Android 程式設計之 AIDL 實例詳解

編輯:Android 開發實例

一般來說,AIDL 這項技術在我們的應用開發過程中並不是很常用。雖然新浪微博提供了 SSO 登錄,但其原理正是使用 AIDL。本文就以一個完整的實例,講述 AIDL 的原理及實現方法。

AIDL(Android 接口描述語言)是一種接口描述語言;編譯器可以透過 aidl 檔生成一段程式碼,透過預先定義的接口達到兩個行程內部通信行程的目的。如果需要在一個 Activity 中存取另一個 Service 中的某個對象,需要先將對象轉化成 AIDL 可識別的參數(可能是多個參數),然後使用 AIDL 來傳遞這些參數;在訊息的接收端,使用這些參數組裝成自己需要的對象。

說白了,AIDL 就是定義一個接口,用戶端(呼叫端)透過 bindService 來與遠程服務端建立一個連線,在該連線建立時會返回一個 IBinder 對象,該對象是服務端 Binder 的 BinderProxy。在建立連線時,用戶端透過 asInterface 函式將該 BinderProxy 對象包裝成本地的 Proxy,並將遠程服務端的 BinderProxy 對象賦值給 Proxy 類別的 mRemote 欄位,就是透過 mRemote 執行遠程方法呼叫。要對 Binder 機制有更深的理解,請參考老羅的 Android 系統行程間通信 Binder 機制在應用程式框架層的 Java 接口原始碼分析。下面我們看一個 AIDL 實例。

AIDL 接口聲明

在 src 目錄下創建一個 com.example.advanceandroid.aidl 包,然後在該包下創建一個 ILogin.aidl 檔,注意是創建檔而不是類別或者接口類型。在 ILogin.aidl 中聲明接口,實例如下:

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

注意看,接口和方法聲明都不用 public,方法加入 public 會提示錯誤。編寫完後,如果 eclipse 開啟了自動編譯,則會在 gen/com.example.advanceandroid.aidl 下生成一個 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; } 

可以看到,該類別中自動生成了 ILogin 接口,該接口中有一個 login() 函式。但最重要的是裡面生成了一個 Stub 類別,該類別繼承了 Binder 類別,並且實現了 ILogin 接口。Stub 裡面最重要的就是 asInterface() 這個函式——在這個函式中會判斷 obj 參數的類型,如果該 obj 是本地的接口類型,則認為不是 IPC,會將該 obj 轉換成 ILogin 類型;否則會透過自動生成的另一個內部類別 Proxy 來包裝 obj,將其賦值給 Proxy 中的 mRemote 屬性。Proxy 類別也實現了 ILogin 接口,在 login() 函式中,Proxy 將透過 Binder 機制向服務端傳遞請求和資料,如上面程式碼中的註釋 2。這是用戶端的工作算是完成了。

服務端 AIDL 接口

服務端也需要在相同的包下創建同名的 aidl 檔,我們直接將用戶端的 com.example.advanceandroid.aidl 包下的 ILogin.aidl 拷貝到服務端即可。如果用到了自定義的類型,那麼該自定義類型也需要在用戶端、服務端都有。拷貝完 aidl 後,在服務端程式中也會在 gen 中生成對應的 ILogin.java 檔,內容同用戶端一樣。這裡的重點我們要看 onTransact 函式,即上述程式碼中的註釋 1 處。可以看到,在 case TRANSACTION_login 處執行了 this.login() 函式,意思是當接收到用戶端的 TRANSACTION_login 請求時,執行 this.login() 函式。透過用戶端的分析我們知道,當我們呼叫 login() 時,實際上就是透過 mRemote 向服務端提交了一個 TRANSACTION_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 * [url=home.php?mod=space&uid=133757]@see[/url] android.app.Service#onBind(android.content.Intent) */ @Override public IBinder onBind(Intent intent) { return mBinder; } } 

該 Service 我們這裡命名為 LoginService,繼承自 Service,然後建一個名為 LoginServiceImpl 的內部類別,該類別繼承自自動生成的 Stub,然後實現 login() 方法。在 LoginService 中聲明一個 IBinder 欄位 mBinder:

 IBinder mBinder = new LoginStubImpl(); 

並且在 LoginService 的 onBind 函式中將 mBinder 對象返回。即在用戶端建立與服務端的連線時,會呼叫 onBind 方法將 mBinder 對象返回,在用戶端的 ServiceConnection 類別的 onServiceConnected 函式中得到的對象 IBinder 就是經過 BinderProxy 包裝的 LoginService 中的 mBinder 對象。因此在服務端中的 onTransact 中呼叫的 this.login() 函式,實際上就是呼叫的 LoginStubImpl 中的 login() 函式。

在服務端程式的 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(ComponentName name, IBinder service) 中的 service 對象是 BinderProxy 類型,經過 asInterface 轉換後被包裝成了 Proxy 類型,但是呼叫的時候,執行的是服務端 LoginStubImpl 中的 login() 函式。因此,LoginStubImpl 實例 mBinder 被服務端包裝成 BinderProxy 類型,再經過用戶端的 Proxy 進行包裝,透過 Binder 機制進行資料傳輸,實現 IPC。

希望本文所述對大家進一步深入掌握 Android 程式設計有所幫助。

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