EventBus初略介绍

来源:互联网 发布:android蓝牙串口源码 编辑:程序博客网 时间:2024/05/29 19:54

什么是EventBus

EventBus是Android下高效的发布/订阅事件总线机制。作用是可以代替传统的Intent,Handler,Broadcast或接口回调函数在Fragment,Activity,Service,线程之间传递数据,执行方法。

特点是代码简洁,是一种发布订阅设计模式(Publish/Subsribe),或称作观察者设计模式。让模块与模块之间解耦。


如何下载

  1. Github主页:https://github.com/greenrobot/EventBus下载源码自行编译jar包
  2. AndroidStudio中之间所有maven依赖eventbus或者build.gradle中添加依赖

     compile 'de.greenrobot:eventbus:2.4.0'

如何使用,分几步?三步

  1. 定义Event 可以是任意Object,用于区分事件类型和传输数据

    public class AnyEventType {    public Object anyData;}
  2. 订阅者注册与注销:

      //注册EventBus.getDefault().register(this);//this为订阅者对象  注册粘性事件: .registerSticky(this);//处理public void onEvent(AnyEventType event){    //Do somethings as you like}public void onEventMainThread(AnyEventType event)public void onEventBackgroundThread(AnyEventType event)public void onEventAsync(AnyEventType event)//注销EventBus.getDefault().unregister(this);//this为订阅者对象
  3. 发布者发布事件:

    //发布EventEventBus.getDefault().post(event);//发布粘性事件:EventBus.getDefault().postSticky(event);//默认post的事件分发完毕会被从内存中删除。postSticky可以将Event另外保存到一个map中put(event.getClass(), event);//通过EventBus.getDefault().getStickyEvent(Class<?> eventType)拿到最后一次发布的Event

EventBus的局限性

无法进程间通信

其他

线程池工具 AsyncExecutor.create()会创建一个线程池并处理线程执行过程中的异常信息,生命周期默认和Application一样。

//执行一个异步任务到线程池AsyncExecutor.create().execute(  new RunnableEx {    public void run throws Exception {      remote.login();      EventBus.getDefault().postSticky(new LoggedInEvent());      // No need to catch Exception    }  }}

混淆配置

-keepclassmembers class ** {    public void onEvent*(***);}# Only required if you use AsyncExecutor-keepclassmembers class * extends de.greenrobot.event.util.ThrowableFailureEvent {    <init>(java.lang.Throwable);}
0 0