Android事件总线 ( AndroidEventBus ) 框架发布

AndroidEventBus Logo AndroidEventBus

如果你不知道事件总线是什么,那么没有关系,下面我们先来看这么一个场景:

你是否在开发的过程中遇到过想在Activity-B中回调Activity-A中的某个函数,但Activity又不能手动创建对象来设置一个Listener什么的? 你是否想在某个Service中想更新Activity或者Fragment中的界面? 等等之类的组件之间的交互问题……

一经思考,你会发现Android中的Activity, Fragment, Service之间的交互是比较麻烦的,可能我们第一想到的是使用广播接收器来在它们之间进行交互。例如上述所说在Activity-B中发一个广播,在Activity-A中注册一个广播接收器来接受该广播。但使用广播接收器稍显麻烦,如果你要将一个实体类当做数据在组件之间传递,那么该实体类还得实现序列化接口,这个成本实在有点高啊!如下所示 :

<code class=" hljs axapta" style="box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; padding: 0.5em; color: rgb(0, 0, 0); border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; display: block; background-color: transparent !important;">    <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// ActivityA中注册广播接收器</span>
    <span class="hljs-class" style="box-sizing: border-box;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">class</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">ActivityA</span> <span class="hljs-inheritance" style="box-sizing: border-box;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">extends</span></span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">Activity</span> {</span>
        @Override
        <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">protected</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> onCreate(Bundle savedInstanceState) {
            <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">super</span>.onCreate(savedInstanceState);

            registerReceiver(<span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">new</span> BroadcastReceiver() {

                @Override
                <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">public</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> onReceive(Context context, Intent intent) {
                    User person = intent.getParcelableExtra(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"user"</span>) ;
                }
            }, <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">new</span> IntentFilter(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"my_action"</span>)) ;
        }
        <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// ...... </span>
    }


    <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// ActivityB中发布广播</span>
    <span class="hljs-class" style="box-sizing: border-box;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">class</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">ActivityB</span> <span class="hljs-inheritance" style="box-sizing: border-box;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">extends</span></span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">Activity</span> {</span>
        @Override
        <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">protected</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> onCreate(Bundle savedInstanceState) {
            <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">super</span>.onCreate(savedInstanceState);


            Intent intent  = <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">new</span> Intent(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"my_action"</span>) ;
            intent.putExtra(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"user"</span>, <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">new</span> User(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"mr.simple"</span>)) ;
            sendBroadcast(intent);
        }
        <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// ...... </span>
    }


    <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// 实体类实现序列化</span>
    <span class="hljs-class" style="box-sizing: border-box;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">class</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">User</span> <span class="hljs-inheritance" style="box-sizing: border-box;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">implements</span></span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">Parcelable</span> {</span>
        String name ;
        <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">public</span> User(String aName) {
            name = aName ;
        }

       <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// 代码省略</span>

        @Override
        <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">public</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> writeToParcel(Parcel dest, <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">int</span> flags) {
            dest.writeString(name);
        }
    }
</code>

是不是有很麻烦的感觉!事件总线框架就是为了简化这些操作,并且降低组件之间的耦合而出现的。 
AndroidEventBus是一个Android平台轻量级的事件总线框架, 它简化了Activity、Fragment、Service等组件之间的交互,很大程度上降低了它们之间的耦合,使得我们的代码更加简洁,耦合性更低,提升我们的代码质量。

在往下看之前,你可以考虑这么一个场景,两个Fragment之间的通信你会怎么实现? 
按照Android官方给的建议的解决方法如下: Communicating with the Activity,思路就是Activity实现某个接口,然后在Fragment-A关联上Activity之后将Activity强转为接口类型,然后在某个时刻Fragment中回调这个接口,然后再从Activity中调用Fragment-B中方法。这个过程是不是有点复杂呢? 如果你也这么觉得,那也就是你继续看下去的理由了。

基本结构

结构图 
AndroidEventBus类似于观察者模式,通过register函数将需要订阅事件的对象注册到事件总线中,然后根据@Subcriber注解来查找对象中的订阅方法,并且将这些订阅方法和订阅对象存储在map中。当用户在某个地方发布一个事件时,事件总线根据事件的参数类型和tag找到对应的订阅者对象,最后执行订阅者对象中的方法。这些订阅方法会执行在用户指定的线程模型中,比如mode=ThreadMode.ASYNC则表示该订阅方法执行在子线程中,更多细节请看下面的说明。

与greenrobot的EventBus的不同

  1. greenrobot的EventBus是一个非常流行的开源库,但是它在使用体验上并不友好,例如它的订阅函数必须以onEvent开头,并且如果需要指定该函数运行的线程则又要根据规则将函数名加上执行线程的模式名,这么说很难理解,比如我要将某个事件的接收函数执行在主线程,那么函数名必须为onEventMainThread。那如果我一个订阅者中有两个参数名相同,且都执行在主线程的接收函数呢? 这个时候似乎它就没法处理了。而且规定死了函数命名,那就不能很好的体现该函数的功能,也就是函数的自文档性。AndroidEventBus使用注解来标识接收函数,这样函数名不受限制,比如我可以把接收函数名写成updateUserInfo(Person info),这样就灵活得多了。
  2. 另一个不同就是AndroidEventBus增加了一个额外的tag来标识每个接收函数可接收的事件的tag,这类似于Broadcast中的action,比如每个Broadcast对应一个或者多个action,当你发广播时你得指定这个广播的action,然后对应的广播接收器才能收到.greenrobot的EventBus只是根据函数参数类型来标识这个函数是否可以接收某个事件,这样导致只要是参数类型相同,任何的事件它都可以接收到,这样的投递原则就很局限了。比如我有两个事件,一个添加用户的事件, 一个删除用户的事件,他们的参数类型都为User,那么greenrobot的EventBus大概是这样的:
<code class=" hljs cs" style="box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; padding: 0.5em; color: rgb(0, 0, 0); border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; display: block; background-color: transparent !important;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">private</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">onEventMainThread</span>(User aUser) {
    <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// code </span>
}</code>

如果你有两个同参数类型的接收函数,并且都要执行在主线程,那如何命名呢 ? 即使你有两个符合要求的函数吧,那么我实际上是添加用户的事件,但是由于EventBus只根据事件参数类型来判断接收函数,因此会导致两个函数都会被执行。AndroidEventBus的策略是为每个事件添加一个tag,参数类型和tag共同标识一个事件的唯一性,这样就确保了事件的精确投递。 
这就是AndroidEventBus和greenrobot的EventBus的不同,但是由于本人对greenrobot的EventBus并不是很了解,很可能上述我所说的有误,如果是那样,欢迎您指出。

AndroidEventBus起初只是为了学习,但是在学习了EventBus的实现之后,发现它在使用上有些不便之处,我想既然我有这些感觉,应该也是有同感之人,在开发群里交流之后,发现确实有这样的情况。因此才将正式地AndroidEventBus以开源库的形式推出来,希望能够帮助到一些需要的人。当然,这个库的成长需要大家的支持与测试,欢迎大家发 pull request。如果你需要的是一个相对成熟、稳定的库,greenrobot的EventBus和square的otto都是非常好的选择。

使用AndroidEventBus

你可以按照下面几个步骤来使用AndroidEventBus.

  • 1 注册事件接收对象
<code class=" hljs java" style="box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; padding: 0.5em; color: rgb(0, 0, 0); border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; display: block; background-color: transparent !important;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">public</span> <span class="hljs-class" style="box-sizing: border-box;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">class</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">YourActivity</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">extends</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">Activity</span> {</span>

    <span class="hljs-annotation" style="box-sizing: border-box; color: rgb(136, 136, 136);">@Override</span>
    <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">protected</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">onCreate</span>(Bundle savedInstanceState) {
        <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">super</span>.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// 注册对象</span>
        EventBus.getDefault().register(<span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">this</span>);
    }

    <span class="hljs-annotation" style="box-sizing: border-box; color: rgb(136, 136, 136);">@Override</span>
    <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">protected</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">onDestroy</span>() {
        <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// 不要忘记注销!!!!</span>
        EventBus.getDefault().unregister(<span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">this</span>);
        <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">super</span>.onDestroy();
    }
}
</code>
  • 2 通过Subscriber注解来标识事件接收对象中的接收方法
<code class=" hljs java" style="box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; padding: 0.5em; color: rgb(0, 0, 0); border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; display: block; background-color: transparent !important;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">public</span> <span class="hljs-class" style="box-sizing: border-box;"><span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">class</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">YourActivity</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">extends</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">Activity</span> {</span>
    <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// code ......</span>

    <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// 接收方法,默认的tag,执行在UI线程</span>
    <span class="hljs-annotation" style="box-sizing: border-box; color: rgb(136, 136, 136);">@Subcriber</span>
    <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">private</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">updateUser</span>(User user) {
        Log.e(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">""</span>, <span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"### update user name = "</span> + user.name);
    }

    <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,执行在UI线程</span>
    <span class="hljs-annotation" style="box-sizing: border-box; color: rgb(136, 136, 136);">@Subcriber</span>(tag = <span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"my_tag"</span>)
    <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">private</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">updateUserWithTag</span>(User user) {
        Log.e(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">""</span>, <span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"### update user with my_tag, name = "</span> + user.name);
    }

    <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,</span>
    <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// post函数在哪个线程执行,该函数就执行在哪个线程    </span>
    <span class="hljs-annotation" style="box-sizing: border-box; color: rgb(136, 136, 136);">@Subcriber</span>(tag = <span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"my_tag"</span>, mode=ThreadMode.POST)
    <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">private</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">updateUserWithMode</span>(User user) {
        Log.e(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">""</span>, <span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"### update user with my_tag, name = "</span> + user.name);
    }

    <span class="hljs-comment" style="box-sizing: border-box; color: rgb(136, 136, 136);">// 含有my_tag,当用户post事件时,只有指定了"my_tag"的事件才会触发该函数,执行在一个独立的线程</span>
    <span class="hljs-annotation" style="box-sizing: border-box; color: rgb(136, 136, 136);">@Subcriber</span>(tag = <span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"my_tag"</span>, mode = ThreadMode.ASYNC)
    <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">private</span> <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">void</span> <span class="hljs-title" style="box-sizing: border-box; color: rgb(136, 0, 0); font-weight: bold;">updateUserAsync</span>(User user) {
        Log.e(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">""</span>, <span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"### update user async , name = "</span> + user.name + <span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">", thread name = "</span> + Thread.currentThread().getName());
    }
}</code>

接收函数使用tag来标识可接收的事件类型,与BroadcastReceiver中指定action是一样的,这样可以精准的投递消息。mode可以指定目标函数执行在哪个线程,默认会执行在UI线程,方便用户更新UI。目标方法执行耗时操作时,可以设置mode为ASYNC,使之执行在子线程中。

  • 3 在其他组件,例如Activity, Fragment,Service中发布事件
<code class=" hljs vhdl" style="box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; padding: 0.5em; color: rgb(0, 0, 0); border-top-left-radius: 0px; border-top-right-radius: 0px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px; display: block; background-color: transparent !important;">    EventBus.getDefault().post(<span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">new</span> User(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"android"</span>));

    // post a event <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">with</span> tag, the tag <span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">is</span> like broadcast<span class="hljs-attribute" style="box-sizing: border-box; color: rgb(136, 136, 255);">'s</span> action
    EventBus.getDefault().post(<span class="hljs-keyword" style="box-sizing: border-box; font-weight: bold;">new</span> User(<span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"mr.simple"</span>), <span class="hljs-string" style="box-sizing: border-box; color: rgb(136, 0, 0);">"my_tag"</span>);</code>

发布事件之后,注册了该事件类型的对象就会接收到响应的事件.

Github链接

欢迎star和fork, AndroidEventBus框架 。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值