1. 程式人生 > >我對AIDL的理解

我對AIDL的理解

       最近一直在研究AIDL,AIDL是為不同程序之間通訊而設計的,它使用了Binder的機制,我這裡不打算講解Binder的原理,因為我也不太清楚安靜。其基本思想就是你的程序(可以稱之為本地端)想呼叫另外一個程序(可稱之為服務端)提供的功能,比如Add。這個時候我們必須建立一個AIDL檔案,假如檔名為IAddService.aidl,內容大致如下:

interface IAddService {
int Add(int a, int b)

}

編譯完成後系統會為這個aidl檔案自動生成IAddService.java,然後在服務端要建立一個IAddService.Stub的Binder例項並實現Add方法,

程式碼大致如下:

IAddService.Stub mBinder = new IAddService.Stub() {
@Override
public int Add(int a, int b) throws RemoteException {
// TODO Auto-generated method stub
return a + b;
}
};

接下來如果本地端能夠拿到這個mBinder例項,就可以呼叫服務端提供的功能了,程式碼大致如下:

IAddService mService;

mService = IAddService.Stub.asInterface(mBinder);

int result = mService.Add(9, 10);

那麼本地怎麼才能拿到服務端建立的那個mBinder例項呢?

一般做法就是在服務端建立一個繼承於Service的類,在該類中去建立之前說的那個mBinder例項,在onBind方法裡返回這個mBinder。

程式碼大致如下:

public class mAIDLService extends Service {

private final IAddService.Stub mBinder = new IAddService.Stub() {

@Override
public int Add(int a, int b) throws RemoteException {
// TODO Auto-generated method stub

return a + b;
}
};

@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;

}

@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//return super.onStartCommand(intent, flags, startId);
}

}

本地端要做的就是去繫結上面說的那個mAIDLService,繫結成功後我們就可以拿到mBinder了,程式碼大致如下:

IAddService mService;

private ServiceConnection mConnection = new ServiceConnection() {

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

// TODO Auto-generated method stub

//這裡就拿到了服務端的那個mBinder

mService = IAddService.Stub.asInterface(service);

                        int result = mService.Add(9, 10);

}

@Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
Log.d("wujiang","disconnect service");
mService = null;  
}

};

                                                            THE END