Android开源框架-EventBus

352 阅读2分钟

今天给大家带来一个android中跨线程通讯框架EventBus使用及源码分析,该框架的使用非常简单,但是需要注意在使用的时候写好注释,要不然后面的人看到这样的数据传递会一脸懵逼的,在阿里的的开发手册中也是推荐使用该框架来进行大数据传递的。阿里开发手册点击这里

EventBus简介

EventBus是一个针对android和java的开源框架,使用更少,更简单的代码实现解耦,减少依赖,更快的开发。该博客基于EventBus V2.2.0,更高的版本源码有一些差异。稍后在EventBus源码分析中会做说明。

EventBus特点

*使用更简单 *使代码更清晰 *更快,更小(60K) *已有1000000000+的应用正在使用 *有多种线程模式

EventBus使用

step1 定义事件

public class MessageEvent{
    /* Additional fields if needed */
}

step2 EventBus注册

订阅方法:在2.2.0的版本中onEvent后面的部分可以有四中写法分别是:MainThread,BackgroundThread,Async和什么都不加。表示在不同的线程中去调用该方法。具体看EventBus的源码解析。

    public void onEventMainThread(MessageEvent event){
        //do something
    }

注册

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

注销

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroy();
    }

step2 发送

        EventBus.getDefault().post(new MessageEvent());

项目中加入EventBus

gradle添加:

    implementation 'org.greenrobot:eventbus:2.2.1'

maven添加

    <dependency>
        <groupId>org.greenrobot</groupId>
        <artifactId>eventbus</artifactId>
        <version>3.2.0</version>
    </dependency>

混淆添加

    -keepattributes *Annotation*
    -keepclassmembers class * {
      @org.greenrobot.eventbus.Subscribe <methods>;
    }
    -keep enum org.greenrobot.eventbus.ThreadMode { *; }
 
    # And if you use AsyncExecutor:
    -keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
        <init>(java.lang.Throwable);
    }

总结

EventBus的使用却是确实更快,更简单的实现了线程间的通讯,数据传递,但是在后续维护中如果没有详细的注释,维护起来会比较麻烦,只能通过全局去搜索。所以“使用的时候一定写好注释!!!”