从AIDL一窥Android Binder机制

Binder机制在Android系统中地位毋庸置疑,system_server就通过Binder来实现进程间的通信,从而达到管理、调用一系列系统服务的能力。本文就AIDL来解读一下Binder机制的。
先了解一下如下几个概念:

IBinder 、 Binder 、 BinderProxy 、 IInterface

  1. IBinder : 根据官方的说明文档IBinder定义的是一种使对象具备远程通信能力的接口,他的子类是Binder。IBinder内部预先定义了一些IPC需要用到的接口,实现IBinder的对象可以被Binder Drivder在IPC过程中传递;
  2. Binder : 实现了IBinder,具备IPC通信的能力。在IPC通信过程中,Binder代表的是Server的本地对象;
  3. BinderProxy : BinderProxy是Binder的内部类,同样实现了IBinder,不同于Binder的是,BinderProxy是Binder对象在Client端的一个代理,用以提供Server具备的接口;
  4. IInterface : 代表的是Server所具备的接口;

还有一点需要说明一下:当一个Service向AMS进行注册时,传递的过去的以及保存在AMS中的是一个Binder对象。当Client需要跟Service进行通信,通过AMS查询到其实是一个BinderProxy,因为可以有多个Client同时跟Service进行通信。当然如果Service和Client在同一进程,AMS返回的还是一个Binder对象,毕竟没有必要进行IPC。在进行IPC时,Binder Drivder会在中间帮忙转换Binder和BinderProxy。

AIDL

还是按照Android Service详解(二)的例子来解释

现在我们来看一下系统自动生成的aidl文件具体有些什么:

/*
 * This file is auto-generated.  DO NOT MODIFY.
 * Original file: /Users/lebens/Development/WorkSpace/jxx_workspace/Server/app/src/main/aidl/jxx/com/server/aidl/IServerServiceInfo.aidl
 */
package jxx.com.server.aidl;
public interface IServerServiceInfo extends android.os.IInterface
{
    /** Local-side IPC implementation stub class. */
    public static abstract class Stub extends android.os.Binder implements jxx.com.server.aidl.IServerServiceInfo
    {
        private static final java.lang.String DESCRIPTOR = "jxx.com.server.aidl.IServerServiceInfo";
        /** Construct the stub at attach it to the interface. */
        public Stub()
        {
            this.attachInterface(this, DESCRIPTOR);
        }
        /**
         * Cast an IBinder object into an jxx.com.server.aidl.IServerServiceInfo interface,
         * generating a proxy if needed.
         */
        public static jxx.com.server.aidl.IServerServiceInfo asInterface(android.os.IBinder obj)
        {
            if ((obj==null)) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin!=null)&&(iin instanceof jxx.com.server.aidl.IServerServiceInfo))) {
                return ((jxx.com.server.aidl.IServerServiceInfo)iin);
            }
            return new jxx.com.server.aidl.IServerServiceInfo.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
        {
            java.lang.String descriptor = DESCRIPTOR;
            switch (code)
            {
                case INTERFACE_TRANSACTION:
                {
                    reply.writeString(descriptor);
                    return true;
                }
                case TRANSACTION_getServerInfo:
                {
                    data.enforceInterface(descriptor);
                    jxx.com.server.aidl.ServerInfo _result = this.getServerInfo();
                    reply.writeNoException();
                    if ((_result!=null)) {
                        reply.writeInt(1);
                        _result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
                    }
                    else {
                        reply.writeInt(0);
                    }
                    return true;
                }
                case TRANSACTION_setServerInfo:
                {
                    data.enforceInterface(descriptor);
                    jxx.com.server.aidl.ServerInfo _arg0;
                    if ((0!=data.readInt())) {
                        _arg0 = jxx.com.server.aidl.ServerInfo.CREATOR.createFromParcel(data);
                    }
                    else {
                        _arg0 = null;
                    }
                    this.setServerInfo(_arg0);
                    reply.writeNoException();
                    if ((_arg0!=null)) {
                        reply.writeInt(1);
                        _arg0.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
                    }
                    else {
                        reply.writeInt(0);
                    }
                    return true;
                }
                default:
                {
                    return super.onTransact(code, data, reply, flags);
                }
            }
        }
        private static class Proxy implements jxx.com.server.aidl.IServerServiceInfo
        {
            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 jxx.com.server.aidl.ServerInfo getServerInfo() throws android.os.RemoteException
            {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                jxx.com.server.aidl.ServerInfo _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    mRemote.transact(Stub.TRANSACTION_getServerInfo, _data, _reply, 0);
                    _reply.readException();
                    if ((0!=_reply.readInt())) {
                        _result = jxx.com.server.aidl.ServerInfo.CREATOR.createFromParcel(_reply);
                    }
                    else {
                        _result = null;
                    }
                }
                finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
            @Override public void setServerInfo(jxx.com.server.aidl.ServerInfo serverinfo) throws android.os.RemoteException
            {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    if ((serverinfo!=null)) {
                        _data.writeInt(1);
                        serverinfo.writeToParcel(_data, 0);
                    }
                    else {
                        _data.writeInt(0);
                    }
                    mRemote.transact(Stub.TRANSACTION_setServerInfo, _data, _reply, 0);
                    _reply.readException();
                    if ((0!=_reply.readInt())) {
                        serverinfo.readFromParcel(_reply);
                    }
                }
                finally {
                    _reply.recycle();
                    _data.recycle();
                }
            }
        }
        static final int TRANSACTION_getServerInfo = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
        static final int TRANSACTION_setServerInfo = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1);
    }
    public jxx.com.server.aidl.ServerInfo getServerInfo() throws android.os.RemoteException;
    public void setServerInfo(jxx.com.server.aidl.ServerInfo serverinfo) throws android.os.RemoteException;
}
  1. 这个文件中,我们看到IServerServiceInfo实现了IInterface,说明IServerServiceInfo具备了IPC通信需要的接口,最底下我们也可以看到定义的getServerInfo()、setServerInfo()两个方法;
  2. 接着来看Stub这个对象,它是IServerServiceInfo的静态内部类,继承了Binder同时实现了IServerServiceInfo。这意味着Stub可以通过Binder Driver进行进程间传递,同时又具备了IPC所需要的接口,实际我们在Service中asBinder()返回的就是这个对象;
  3. Proxy对象,这又是一个代理对象,不过代理的是BinderProxy。这个对象存在的意思就是代理BinderProxy,将Client的操作转化成BinderProxy去跟Server通信。
  4. Proxy 和 Stub 的区别在于,Stud本身就是一个Binder对象,可以直接被Binder Driver传递,而Proxy只是代表Service提供的IPC接口,实际使用内部的被代理的mRemote来实现IPC。
Stub

关于Stub再来看几点:

  1. DESCRIPTOR : 这是用来唯一表示Stub的,当Stub被实例化时会通过DESCRIPTOR来保存owner对象,也就是Stub所代表的IInterface,同时在queryLocalInterface如果是在同一进程查询的话就是返回的Stub;
  2. TRANSACTION_getServerInfo 、 TRANSACTION_setServerInfo : 这两个用来标识Client操作的接口方法。
  3. asInterface : 这个方法就是将Binder,转换成Client需要的接口对象,如果Binder Driver返回的是一个BinderProxy对象,则创建一个Proxy返回给Client。
  4. onTransact : 这个方法跟下面的Proxy对象一同分析。
Proxy
  1. mRemote : 这是一个BinderProxy对象,由Binder Driver传递而来。Proxy的IPC都是通过mRemote来实现的;
  2. 这里我们还看到的了我们定义的接口方法,这些方法都是提供给Client使用的,用于跟Server通信;
  3. mRemote的transact() : 在Binder Driver的帮助下,最终会调用到Stub的onTransact()中。
onTransact()

以getServerInfo()为例来分析一下onTransact传递过程。
首先我们在Proxy的实现是这样的

    @Override public jxx.com.server.aidl.ServerInfo getServerInfo() throws android.os.RemoteException
    {
        android.os.Parcel _data = android.os.Parcel.obtain();
        android.os.Parcel _reply = android.os.Parcel.obtain();
        jxx.com.server.aidl.ServerInfo _result;
        try {
            _data.writeInterfaceToken(DESCRIPTOR);
            mRemote.transact(IServerServiceInfo.Stub.TRANSACTION_getServerInfo, _data, _reply, 0);
            _reply.readException();
            if ((0!=_reply.readInt())) {
                _result = jxx.com.server.aidl.ServerInfo.CREATOR.createFromParcel(_reply);
            }
            else {
                _result = null;
            }
        }
        finally {
            _reply.recycle();
            _data.recycle();
        }
        return _result;
    }
  1. _data 、 _reply 分别用于Client向Server传递参数和Server向Client返回结果,这2个内的参数都是要序列化的,毕竟IPC;
  2. 通过mRemote.transact开始调用Server的方法;
  3. 通过_reply读取Server返回的数据,并反序列化结果,将之返回;

从上面的分析可以知道,这里的mRemote其实是一个BinderProxy对象,我们去看一下这个方法

/**
     * Default implementation rewinds the parcels and calls onTransact.  On
     * the remote side, transact calls into the binder to do the IPC.
     */
    public final boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply,
            int flags) throws RemoteException {
        if (false) Log.v("Binder", "Transact: " + code + " to " + this);

        if (data != null) {
            data.setDataPosition(0);
        }
        boolean r = onTransact(code, data, reply, flags);
        if (reply != null) {
            reply.setDataPosition(0);
        }
        return r;
    }

最终调用的是Binder内的onTransact(),也就是Stub的onTransact(),我们来看一下

@Override public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException
        {
            java.lang.String descriptor = DESCRIPTOR;
            switch (code)
            {
                case INTERFACE_TRANSACTION:
                {
                    reply.writeString(descriptor);
                    return true;
                }
                case TRANSACTION_getServerInfo:
                {
                    data.enforceInterface(descriptor);
                    jxx.com.server.aidl.ServerInfo _result = this.getServerInfo();
                    reply.writeNoException();
                    if ((_result!=null)) {
                        reply.writeInt(1);
                        _result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
                    }
                    else {
                        reply.writeInt(0);
                    }
                    return true;
                }
                case TRANSACTION_setServerInfo:
                {
                    data.enforceInterface(descriptor);
                    jxx.com.server.aidl.ServerInfo _arg0;
                    if ((0!=data.readInt())) {
                        _arg0 = jxx.com.server.aidl.ServerInfo.CREATOR.createFromParcel(data);
                    }
                    else {
                        _arg0 = null;
                    }
                    this.setServerInfo(_arg0);
                    reply.writeNoException();
                    if ((_arg0!=null)) {
                        reply.writeInt(1);
                        _arg0.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
                    }
                    else {
                        reply.writeInt(0);
                    }
                    return true;
                }
                default:
                {
                    return super.onTransact(code, data, reply, flags);
                }
            }

在内部可以看到case TRANSACTION_getServerInfo 下的操作其实也是很简单,就是把Client需要的结果通过reply传递回Client

总结

通过上面的代码分析,AIDL我们可以快速实现IPC,我们来总结一下:

  1. Server需要定义提供给Client的接口,也即实现IInterface,同时还要提供一个Binder用来供Binder Driver找到Server,通过DESCRIPTOR确定;
  2. Client在跟Server通信之前需要获得一个Binder或者BinderProxy对象,通过Binder Driver跟Server建立联系;
  3. Binder Driver在通信过程中自动转换了BinderProxy 和 Binder;

通过这个例子的分析,其实系统的AMS管理各种系统服务也是同样的套路,通过2个Binder建立通信。

还有一点需要注意:
Binder或者BinderProxy都是运行在他们自己的Binder池中的,也就是直接通过Binder通信的话,需要注意线程切换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android Binder 机制Android 系统中的一种进程间通信(IPC)机制,用于在不同的进程之间传递数据和调用方法。它是 Android 系统中最重要的 IPC 机制之一,也是 Android 应用程序与系统服务进行通信的基础。 Binder 机制的工作原理是基于一个抽象的客户端-服务器模型。在 Binder 机制中,有三种角色:客户端、服务器和服务管理器。客户端和服务器在不同的进程中运行,而服务管理器运行在系统服务进程中。 当客户端需要与服务器通信时,它首先通过服务管理器获取服务器的引用。服务管理器通过一个名为 Binder 驱动的内核模块来实现进程间通信。客户端可以通过跨进程访问服务器对象来调用服务器上的方法,并将参数传递给服务器。服务器可以将结果返回给客户端。 Binder 机制的一个重要特性是它支持跨进程的对象引用。这意味着客户端可以获取服务器上的对象引用,并将其传递给其他进程中的客户端。通过这种方式,多个客户端可以共享服务器上的相同对象,并相互协作。 在 Android 应用程序中,开发者可以通过 AIDLAndroid 接口定义语言)来定义客户端和服务器之间的接口。AIDL 可以生成一个 Java 接口和一个 C++ 接口,用于在客户端和服务器之间进行通信。 总之,Android Binder 机制Android 系统中用于进程间通信的核心技术之一。它提供了一种高效、灵活和安全的方式来在不同的进程之间传递数据和调用方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值