Android的Binder机制

前言

无聊看了下别人的面试题,发现binder经常被问到,于是打算将它写下了方便明年面试的时候复习。而且我发现有些东西看了就忘(就像binder之前看了N遍)如果你写下来的话就不会那么容易忘了(自我安慰...)

概述

Binder一个实现了IBinder接口的类,从IPC角度来看,他是Android中的一种跨进程通讯方式

  • 从Android Framework角度看,他是ServiceManager链接各种Manager和相应ManagerService的桥梁
  • 从Android应用层角度来看,Binder是客户端和服务端进行通信的媒介

**下面用AIDL分析Binder的工作机制 **

  1. 首先创建以下三个类Student.java Student.aidl ShowMessage.aidl代码
//Student.java
public class Student implements Parcelable{
    public String name;
    public String id;

    public Student(String name, String id) {
        this.name = name;
        this.id = id;
    }

    protected Student(Parcel in) {
        name = in.readString();
        id = in.readString();
    }

    public static final Creator<Student> CREATOR = new Creator<Student>() {
        @Override
        public Student createFromParcel(Parcel in) {
            return new Student(in);
        }

        @Override
        public Student[] newArray(int size) {
            return new Student[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeString(id);
    }

    public String getName() {
        return name;
    }

    public String getId() {
        return id;
    }
}

// Student.aidl
package com.example.luoweidong.binder;
parcelable Student;

// ShowMessage.aidl
package com.example.luoweidong.binder;
import com.example.luoweidong.binder.Student;
interface ShowMessage {
    String showMessage(in Student student);
}

2: 然后在会看到在build/generated/source/aidl/debug系统会生成一个接口,代码如下

public interface ShowMessage extends android.os.IInterface {
    /**
     * Local-side IPC implementation stub class.
     */
    public static abstract class Stub extends android.os.Binder implements com.example.luoweidong.binder.ShowMessage {
        private static final java.lang.String DESCRIPTOR = "com.example.luoweidong.binder.ShowMessage";

        /**
         * Construct the stub at attach it to the interface.
         */
        public Stub() {
            this.attachInterface(this, DESCRIPTOR);
        }

        /**
         * Cast an IBinder object into an com.example.luoweidong.binder.ShowMessage interface,
         * generating a proxy if needed.
         */
        public static com.example.luoweidong.binder.ShowMessage asInterface(android.os.IBinder obj) {
            if ((obj == null)) {
                return null;
            }
            android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof com.example.luoweidong.binder.ShowMessage))) {
                return ((com.example.luoweidong.binder.ShowMessage) iin);
            }
            return new com.example.luoweidong.binder.ShowMessage.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 {
            switch (code) {
                case INTERFACE_TRANSACTION: {
                    reply.writeString(DESCRIPTOR);
                    return true;
                }
                case TRANSACTION_showMessage: {
                    data.enforceInterface(DESCRIPTOR);
                    com.example.luoweidong.binder.Student _arg0;
                    if ((0 != data.readInt())) {
                        _arg0 = com.example.luoweidong.binder.Student.CREATOR.createFromParcel(data);
                    } else {
                        _arg0 = null;
                    }
                    java.lang.String _result = this.showMessage(_arg0);
                    reply.writeNoException();
                    reply.writeString(_result);
                    return true;
                }
            }
            return super.onTransact(code, data, reply, flags);
        }

        private static class Proxy implements com.example.luoweidong.binder.ShowMessage {
            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 java.lang.String showMessage(com.example.luoweidong.binder.Student student) throws android.os.RemoteException {
                android.os.Parcel _data = android.os.Parcel.obtain();
                android.os.Parcel _reply = android.os.Parcel.obtain();
                java.lang.String _result;
                try {
                    _data.writeInterfaceToken(DESCRIPTOR);
                    if ((student != null)) {
                        _data.writeInt(1);
                        student.writeToParcel(_data, 0);
                    } else {
                        _data.writeInt(0);
                    }
                    mRemote.transact(Stub.TRANSACTION_showMessage, _data, _reply, 0);
                    _reply.readException();
                    _result = _reply.readString();
                } finally {
                    _reply.recycle();
                    _data.recycle();
                }
                return _result;
            }
        }

        static final int TRANSACTION_showMessage = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0);
    }

    public java.lang.String showMessage(com.example.luoweidong.binder.Student student) throws android.os.RemoteException;
}

** 我们一点一点来分析他生成的源码 **

  • 我们可以看到他是一个实现了IInterface的接口,想要在Binder中传输的接口都必须要实现他
  • 往下看声明了一个继承Binder的内部类Stub,当客户端和服务端在同一个进程时,方法调用不会调用transact,当不在同一个进程会调用transact(这个方法主要用来发送一些数据和一些描述它内容的元数据,对应有个OnTransact方法),这些逻辑由代理类Proxy完成
  • 往下声明了一个DESCRIPTOR静态变量,他是用来标识Binder
  • 往下声明了一个asInterface方法,当我们使用AIDL的时候就是用这方法将服务端返回的IBinder对象转换成我们需要的AIDL接口类型对象,这转换是区分是进程的,如果客户端和服务端在同一个进程那么这个方法返回的就是服务端的Stub本身,
android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR);
            if (((iin != null) && (iin instanceof com.example.luoweidong.binder.ShowMessage))) {
                return ((com.example.luoweidong.binder.ShowMessage) iin);
            }

否者返回的是封装好的Stub.proxy对象

return new com.example.luoweidong.binder.ShowMessage.Stub.Proxy(obj);
  • 往下声明了一个asBinder方法,就是返回当前Binder对象
  • 往下声明了一个onTransact方法,他会根据请求码响应客户端的请求,我们来分析一下TRANSACTION_showMessage这个请求码里面的代码他就是首先从data中取出调用该方法所需要的参数,如果没有置为空然后将结果写入reply
  • 接下来看到了一个代理类Proxy,看他的构造方法传入了一个remote ,IBinder 类型的参数,也就是我们调用的asInterface时候传入来的客户端的IBinder类型的变量,所以他是运行在客户端,所以远程调用的时候不能在主线程中做耗时任务,接下来看他里面实现的方法showMessage()方法,_data是输入数据,_reply,是用来读取结果并将它赋值给_result返回给客户端
  • 倒数第二行代码我们看到定义了一个变量TRANSACTION_showMessage这个是用来标记我们的方法的
  • 在最后一行代码中我们可以看见,他声明了一个showMessage ()方法,这也是我们在AIDL文件中声明的方法

分析完生成的源码之后我们发现其实还是挺简单的,所以遇到源码什么的不要慌,静下心来慢慢看就可以了

概括

我们在平常中经常会用到ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);那么在这中间Binder是如何运转的呢

  • 我们知道任何Service使用之前,都要向SM注册(就像上面生成的字符串就是用来唯一标识的)
  • 当客户端要访问Service时,首先要向SM查询得到具体的引用,然后客户端就调用该引用去向服务端发送请求。
  • 而且Client、Server和Service Manager运行在用户空间,Binder驱动程序运行内核空间,因为不在同一个进程中的它们的资源是不共享的,所以Binder驱动程序的作用就是提供设备文件/dev/binder与用户空间交互,Client、Server和Service Manager通过open和ioctl文件操作函数与Binder驱动程序进行通信

他们之间的关系如下(引用老罗的图)

Binder机制.gif

想继续深入学习的话可以看这些文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容