AIDL(Android Interface Definel),進(jìn)程件通信機(jī)制,使用IPC原理
前一段時(shí)間在研究Android Binder機(jī)制,順便復(fù)習(xí)一下AIDL霞势。
再講述這個(gè)之前需要先啰嗦一下服務(wù)綁定赐稽。http://blog.csdn.net/singwhatiwanna/article/details/9058143看這篇文章就可以了。
其實(shí)組要差別就是在于通過(guò)綁定不在同一個(gè)進(jìn)程內(nèi)的服務(wù)來(lái)實(shí)現(xiàn)不同進(jìn)程間的通信实幕。這個(gè)時(shí)候我們需要使用的就是AIDL。如何實(shí)現(xiàn)不同進(jìn)程見(jiàn)得通信我們?cè)谇懊娴腂inder機(jī)制的解析中已經(jīng)講過(guò)了,想了解的看前面的文章吧屎即!所以AIDL其實(shí)就是Binder機(jī)制的Java實(shí)現(xiàn)。
那么先來(lái)將一下AIDL的使用吧事富!根據(jù)官方API技俐,有三步:
- 創(chuàng)建.aidl文件
- 實(shí)現(xiàn).aidl文件內(nèi)申明的服務(wù)接口
- 將該借口暴露給Client
創(chuàng)建.aidl文件
AS創(chuàng)建很簡(jiǎn)單,直接 new——> Folder——>AIDL Folder统台,new——>AIDL File雕擂。
使用Java語(yǔ)言編寫(xiě),具體細(xì)節(jié)看官方API吧贱勃!然后點(diǎn)擊Make Profile
或`Ctrl+F9井赌,生成Java文件。
具體實(shí)現(xiàn)如下:
public interface MyInterface extends android.os.IInterface{
public static abstract class Stub extends android.os.Binder implements com.example.aidlservice.MyInterface{
贵扰。仇穗。。戚绕。纹坐。。
}
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, java.lang.String aString) throws android.os.RemoteException;
public int add(int num1, int num2) throws android.os.RemoteException;
}
解釋一下吧舞丛!因?yàn)檫@是我們需要研究的重點(diǎn)耘子。
Stub 類封裝了IPC機(jī)制的發(fā)部分功能果漾,它繼承了Binder類實(shí)現(xiàn)了aidl文件中自定的接口。
實(shí)現(xiàn)服務(wù)接口
創(chuàng)建一個(gè)自定義Service谷誓,實(shí)現(xiàn)服務(wù)接口绒障,其實(shí)就是定義一個(gè)IBInder對(duì)象而已
private final IRemoteService.Stub mBinder = new IRemoteService.Stub() { public int getPid(){ return Process.myPid(); } public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) { // Does nothing }};
暴露給Client
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return iBinder;
}
private IBinder iBinder = new MyInterface.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException { }
@Override
public int add(int num1, int num2) throws RemoteException {
Log.d(TAG, "add: 收到了遠(yuǎn)程請(qǐng)求,輸入?yún)?shù):num1="+num1+",\n num2="+num2);
return num1+num2;
}
};
}
最終實(shí)現(xiàn)了下面這種奇怪的類間關(guān)系
感覺(jué)很奇怪是不是捍歪,但是是不是很像以前將的ServiceManager對(duì)象類關(guān)系圖盎琛!所以通過(guò)這種Proxy/Stub(存根)模式更具有安全性费封』烂睿可以很好的實(shí)現(xiàn)Binder通信機(jī)制蒋伦。