使用AIDL實現進程間的通信 (轉載liuhe688)

使用AIDL實現進程間的通信

在Android中,如果我們需要在不同進程間實現通信,就需要用到AIDL技術去完成。

AIDL(Android Interface Definition Language)是一種接口定義語言,編譯器通過*.aidl文件的描述信息生成符合通信協議的Java代碼,我們無需自己去寫這段繁雜的代碼,只需要在需要的時候調用即可,通過這種方式我們就可以完成進程間的通信工作。關於AIDL的編寫規則我在這裏就不多介紹了,讀者可以到網上查找一下相關資料。

接下來,我就演示一個操作AIDL的最基本的流程。

首先,我們需要建立一個服務端的工程,如圖所以:

 

在IPerson.aidl中我們定義了一個“問候”的方法,代碼如下:

  1. package com.scott.aidl;  
  2. interface IPerson {  
  3.     String greet(String someone);  
  4. }  

在Eclipse插件的幫助下,編譯器會自動在gen目錄中生成對應的IPerson.java文件,格式化後的代碼如下:

  1. package com.scott.aidl;  
  2.   
  3. public interface IPerson extends android.os.IInterface {  
  4.     /** Local-side IPC implementation stub class. */  
  5.     public static abstract class Stub extends android.os.Binder implements com.scott.aidl.IPerson {  
  6.           
  7.         private static final java.lang.String DESCRIPTOR = "com.scott.aidl.IPerson";  
  8.   
  9.         /** Construct the stub at attach it to the interface. */  
  10.         public Stub() {  
  11.             this.attachInterface(this, DESCRIPTOR);  
  12.         }  
  13.   
  14.         /** 
  15.          * Cast an IBinder object into an com.scott.aidl.IPerson interface, 
  16.          * generating a proxy if needed. 
  17.          */  
  18.         public static com.scott.aidl.IPerson asInterface(android.os.IBinder obj) {  
  19.             if ((obj == null)) {  
  20.                 return null;  
  21.             }  
  22.             android.os.IInterface iin = (android.os.IInterface) obj.queryLocalInterface(DESCRIPTOR);  
  23.             if (((iin != null) && (iin instanceof com.scott.aidl.IPerson))) {  
  24.                 return ((com.scott.aidl.IPerson) iin);  
  25.             }  
  26.             return new com.scott.aidl.IPerson.Stub.Proxy(obj);  
  27.         }  
  28.   
  29.         public android.os.IBinder asBinder() {  
  30.             return this;  
  31.         }  
  32.   
  33.         @Override  
  34.         public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags)  
  35.                 throws android.os.RemoteException {  
  36.             switch (code) {  
  37.             case INTERFACE_TRANSACTION: {  
  38.                 reply.writeString(DESCRIPTOR);  
  39.                 return true;  
  40.             }  
  41.             case TRANSACTION_greet: {  
  42.                 data.enforceInterface(DESCRIPTOR);  
  43.                 java.lang.String _arg0;  
  44.                 _arg0 = data.readString();  
  45.                 java.lang.String _result = this.greet(_arg0);  
  46.                 reply.writeNoException();  
  47.                 reply.writeString(_result);  
  48.                 return true;  
  49.             }  
  50.             }  
  51.             return super.onTransact(code, data, reply, flags);  
  52.         }  
  53.   
  54.         private static class Proxy implements com.scott.aidl.IPerson {  
  55.             private android.os.IBinder mRemote;  
  56.   
  57.             Proxy(android.os.IBinder remote) {  
  58.                 mRemote = remote;  
  59.             }  
  60.   
  61.             public android.os.IBinder asBinder() {  
  62.                 return mRemote;  
  63.             }  
  64.   
  65.             public java.lang.String getInterfaceDescriptor() {  
  66.                 return DESCRIPTOR;  
  67.             }  
  68.   
  69.             public java.lang.String greet(java.lang.String someone) throws android.os.RemoteException {  
  70.                 android.os.Parcel _data = android.os.Parcel.obtain();  
  71.                 android.os.Parcel _reply = android.os.Parcel.obtain();  
  72.                 java.lang.String _result;  
  73.                 try {  
  74.                     _data.writeInterfaceToken(DESCRIPTOR);  
  75.                     _data.writeString(someone);  
  76.                     mRemote.transact(Stub.TRANSACTION_greet, _data, _reply, 0);  
  77.                     _reply.readException();  
  78.                     _result = _reply.readString();  
  79.                 } finally {  
  80.                     _reply.recycle();  
  81.                     _data.recycle();  
  82.                 }  
  83.                 return _result;  
  84.             }  
  85.         }  
  86.   
  87.         static final int TRANSACTION_greet = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);  
  88.     }  
  89.   
  90.     public java.lang.String greet(java.lang.String someone) throws android.os.RemoteException;  
  91. }  

該文件的大綱視圖如下:

IPerson接口中的抽象內部類Stub繼承android.os.Binder類並實現IPerson接口,比較重要的方法是asInterface(IBinder)方法,該方法會將IBinder類型的對象轉換成IPerson類型,必要的時候生成一個代理對象返回結果。

接下來就是我們的Service了:

  1. package com.scott.server;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.os.IBinder;  
  6. import android.os.RemoteException;  
  7. import android.util.Log;  
  8.   
  9. import com.scott.aidl.IPerson;  
  10.   
  11. public class AIDLService extends Service {  
  12.   
  13.     private static final String TAG = "AIDLService";  
  14.       
  15.     IPerson.Stub stub = new IPerson.Stub() {  
  16.         @Override  
  17.         public String greet(String someone) throws RemoteException {  
  18.             Log.i(TAG, "greet() called");  
  19.             return "hello, " + someone;  
  20.         }  
  21.     };  
  22.       
  23.     @Override  
  24.     public IBinder onBind(Intent intent) {  
  25.         Log.i(TAG, "onBind() called");  
  26.         return stub;  
  27.     }  
  28.       
  29.     @Override  
  30.     public boolean onUnbind(Intent intent) {  
  31.         Log.i(TAG, "onUnbind() called");  
  32.         return true;  
  33.     }  
  34.       
  35.     @Override  
  36.     public void onDestroy() {  
  37.         super.onDestroy();  
  38.         Log.i(TAG, "onDestroy() called");  
  39.     }  
  40. }  

我們實現了IPerson.Stub這個抽象類的greet方法,然後再onBind(Intent)方法中返回我們的stub實例,這樣一來調用方獲取的IPerson.Stub就是我們的這個實例,greet方法也會按照我們的期望那樣執行。

當然,要想讓Service生效,我們還需要在AndroidManifest.xml中做一些配置工作:

  1. <service android:name=".AIDLService">  
  2.     <intent-filter>  
  3.         <action android:name="android.intent.action.AIDLService" />  
  4.              <category android:name="android.intent.category.DEFAULT" />  
  5.     </intent-filter>  
  6. </service>  

服務端已經完成了,接下來我們就該完成客戶端的工作了。我已經建好了一個客戶端工程,如圖:

我們只需要把IPerson.aidl文件拷到相應的目錄中即可,編譯器同樣會生成相對應的IPerson.java文件,這一部分和服務端沒什麼區別。這樣一來,服務端和客戶端就在通信協議上達到了統一。我們主要工作在MainActivity中完成。

MainActivity代碼如下:

  1. package com.scott.client;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.ComponentName;  
  5. import android.content.Context;  
  6. import android.content.Intent;  
  7. import android.content.ServiceConnection;  
  8. import android.os.Bundle;  
  9. import android.os.IBinder;  
  10. import android.os.RemoteException;  
  11. import android.util.Log;  
  12. import android.view.View;  
  13. import android.widget.Button;  
  14. import android.widget.Toast;  
  15.   
  16. import com.scott.aidl.IPerson;  
  17.   
  18. public class MainActivity extends Activity {  
  19.   
  20.     private Button bindBtn;  
  21.     private Button greetBtn;  
  22.     private Button unbindBtn;  
  23.   
  24.     private IPerson person;  
  25.     private ServiceConnection conn = new ServiceConnection() {  
  26.   
  27.         @Override  
  28.         public void onServiceConnected(ComponentName name, IBinder service) {  
  29.             Log.i("ServiceConnection""onServiceConnected() called");  
  30.             person = IPerson.Stub.asInterface(service);  
  31.         }  
  32.   
  33.         @Override  
  34.         public void onServiceDisconnected(ComponentName name) {  
  35.             //This is called when the connection with the service has been unexpectedly disconnected,  
  36.             //that is, its process crashed. Because it is running in our same process, we should never see this happen.  
  37.             Log.i("ServiceConnection""onServiceDisconnected() called");  
  38.         }  
  39.     };  
  40.   
  41.     @Override  
  42.     public void onCreate(Bundle savedInstanceState) {  
  43.         super.onCreate(savedInstanceState);  
  44.         setContentView(R.layout.main);  
  45.   
  46.         bindBtn = (Button) findViewById(R.id.bindBtn);  
  47.         bindBtn.setOnClickListener(new View.OnClickListener() {  
  48.             @Override  
  49.             public void onClick(View v) {  
  50.                 Intent intent = new Intent("android.intent.action.AIDLService");  
  51.                 bindService(intent, conn, Context.BIND_AUTO_CREATE);  
  52.                   
  53.                 bindBtn.setEnabled(false);  
  54.                 greetBtn.setEnabled(true);  
  55.                 unbindBtn.setEnabled(true);  
  56.             }  
  57.         });  
  58.   
  59.         greetBtn = (Button) findViewById(R.id.greetBtn);  
  60.         greetBtn.setOnClickListener(new View.OnClickListener() {  
  61.             @Override  
  62.             public void onClick(View v) {  
  63.                 try {  
  64.                     String retVal = person.greet("scott");  
  65.                     Toast.makeText(MainActivity.this, retVal, Toast.LENGTH_SHORT).show();  
  66.                 } catch (RemoteException e) {  
  67.                     Toast.makeText(MainActivity.this"error", Toast.LENGTH_SHORT).show();  
  68.                 }  
  69.             }  
  70.         });  
  71.   
  72.         unbindBtn = (Button) findViewById(R.id.unbindBtn);  
  73.         unbindBtn.setOnClickListener(new View.OnClickListener() {  
  74.             @Override  
  75.             public void onClick(View v) {  
  76.                 unbindService(conn);  
  77.                   
  78.                 bindBtn.setEnabled(true);  
  79.                 greetBtn.setEnabled(false);  
  80.                 unbindBtn.setEnabled(false);  
  81.             }  
  82.         });  
  83.     }  
  84. }  

從代碼中可以看到,我們要重寫ServiceConnection中的onServiceConnected方法將IBinder類型的對像轉換成我們的IPerson類型。到現在我們就剩下最後一個步驟了,這個環節也是最爲關鍵的,就是綁定我們需要的服務。我們通過服務端Service定義的“android.intent.action.AIDLService”這個標識符來綁定其服務,這樣客戶端和服務端就實現了通信的連接,我們就可以調用IPerson中的“問候”方法了。

最後,貼幾張客戶端演示過程圖。

 

 

 

 按照順序分別是:初始界面;點擊bindService後界面;點擊greet後界面;點擊unbindService後界面。

操作過程中的日誌如下:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章