Android AIDL分析

AIDL(Android Interface Definel),进程件通信机制,使用IPC原理

前一段时间在研究Android Binder机制,顺便复习一下AIDL。
再讲述这个之前需要先啰嗦一下服务绑定。http://blog.csdn.net/singwhatiwanna/article/details/9058143看这篇文章就可以了。

其实组要差别就是在于通过绑定不在同一个进程内的服务来实现不同进程间的通信。这个时候我们需要使用的就是AIDL。如何实现不同进程见得通信我们在前面的Binder机制的解析中已经讲过了,想了解的看前面的文章吧!所以AIDL其实就是Binder机制的Java实现。

那么先来将一下AIDL的使用吧!根据官方API,有三步:

  • 创建.aidl文件
  • 实现.aidl文件内申明的服务接口
  • 将该借口暴露给Client

创建.aidl文件

AS创建很简单,直接 new——> Folder——>AIDL Folder,new——>AIDL File。
使用Java语言编写,具体细节看官方API吧!然后点击Make Profile或`Ctrl+F9,生成Java文件。
具体实现如下:

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;
}

解释一下吧!因为这是我们需要研究的重点。
Stub 类封装了IPC机制的发部分功能,它继承了Binder类实现了aidl文件中自定的接口。

实现服务接口

创建一个自定义Service,实现服务接口,其实就是定义一个IBInder对象而已

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: 收到了远程请求,输入参数:num1="+num1+",\n num2="+num2);           
      return num1+num2;        
    }    
  };
}

最终实现了下面这种奇怪的类间关系

Android AIDL分析_第1张图片
aidl.jpeg

感觉很奇怪是不是,但是是不是很像以前将的ServiceManager对象类关系图啊!所以通过这种Proxy/Stub(存根)模式更具有安全性。可以很好的实现Binder通信机制。

你可能感兴趣的:(Android AIDL分析)