# EventBus2.0 **Repository Path**: HackerX9/EventBus2.0 ## Basic Information - **Project Name**: EventBus2.0 - **Description**: 2.0 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2017-11-06 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # EventBus单例模式 目前EventBus只支持跨线程,而不支持跨进程. EventBus是一个消息总线,以观察者模式实现,用于简化程序的组件、线程通信,可以轻易切换线程、开辟线程,EventBus3.0跟先前版本的区别在于加入了annotation @Subscribe,取代了以前约定命名的方式. ## 加速模式 1. app--->build.gradle ``` apply plugin: 'com.android.application' // EventBus apply plugin: 'com.neenbedankt.android-apt' // EventBus dependencies { // EventBus compile 'org.greenrobot:eventbus:3.0.0' apt 'org.greenrobot:eventbus-annotation-processor:3.0.1' // EventBus } // EventBus apt { arguments { eventBusIndex "com.palfund.eventbus.GenEventBusIndex" } } // EventBus ``` 2. project--->build.gradle ``` dependencies { classpath 'com.android.tools.build:gradle:2.0.0' // EventBus classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' // EventBus } ``` 3. 启用加速模式 addIndex(new GenEventBusIndex())启用加速模式,在Application启动的时候就调用这行代码保证之后所有的EventBus都默认使用了加速模式 EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).addIndex(new GenEventBusIndex()).installDefaultEventBus(); ## 接收消息 ``` // 注册,首先通过注解获取到订阅者中所有的事件处理方法的集合List,然后遍历 // 事件处理方法的集合进行订阅(利用订阅者和事件处理方法创建订阅对象subscription,首先从 // HashMap:Map,CopyOnWriteArrayList>subscriptionsByEventType事件-订阅集合 中根据事件eventType // 获取事件订阅的集合CopyOnWriteArrayList subscriptions,如果集合为null则说明此事件没有添加过, // 创建事件订阅集合,并将事件eventType、事件订阅集合CopyOnWriteArrayList // subscriptions添加到map中并将订阅对象subscription添加到事件订阅集合subscriptions中;然后从Map>>typesBySubscriber // 订阅者-事件集合中,根据订阅者获取事件集合为null,则说明没有添加过,则创建集合并将订阅者、事件集合添加到map中,并将事件添加到事件集合中 EventBus.getDefault().register(this); // 接收方法 @Subscribe public void onMessageEvent(MessageEvent message) { Toast.makeText(this, "" + message.mMessage, Toast.LENGTH_SHORT).show(); } // 取消注册 // 首先订阅者-事件map通过订阅者获取相应的事件集合subscribedTypes,遍历事件集合利用订阅者和事件, // 从事件-订阅集合map中根据事件获取到订阅集合list,遍历订阅集合如果订阅的订阅者和传入的订阅者相同,则从订阅集合list中移除此订阅 EventBus.getDefault().unregister(this); ``` ## 发送消息 ``` EventBus.getDefault().post(new MessageEvent("post")); // postSticky()在内存中保存最新的消息,取消原有消息,执行最新消息,只有在注册后才会执行,如果没有注册,消息会一直保留来内存中. // stickyEvents.put(event.getClass(), event); EventBus.getDefault().postSticky(new MessageEvent("postSticky" + (count++))); ``` ## 取消stickyEvent ``` MessageEvent stickyEvent = EventBus.getDefault().getStickyEvent(MessageEvent.class); // Better check that an event was actually posted before if(stickyEvent != null) { // "Consume" the sticky event EventBus.getDefault().removeStickyEvent(stickyEvent); //or EventBus.getDefault().removeAllStickyEvents(); // Now do something with it } ``` ## ThreadMode 1. ThreadMode.POSTING ``` //默认调用方式,在调用post方法的线程执行,避免了线程切换,性能开销最少 // Called in the same thread (default) @Subscribe(threadMode = ThreadMode.POSTING) // ThreadMode is optional here public void onMessage(MessageEvent event) { log(event.message); } ``` 2. ThreadMode.MAIN ``` // Called in Android UI's main thread @Subscribe(threadMode = ThreadMode.MAIN) public void onMessage(MessageEvent event) { textField.setText(event.message); } ``` 3. ThreadMode.BACKGROUND ``` // 如果调用post方法的线程不是主线程,则直接在该线程执行 // 如果是主线程,则切换到后台单例线程,多个方法公用同个后台线程,按顺序执行,避免耗时操作 // Called in the background thread @Subscribe(threadMode = ThreadMode.BACKGROUND) public void onMessage(MessageEvent event){ saveToDisk(event.message); } ``` 4. ThreadMode.ASYNC ``` //开辟新独立线程,用来执行耗时操作,例如网络访问 //EventBus内部使用了线程池,但是要尽量避免大量长时间运行的异步线程,限制并发线程数量 //可以通过EventBusBuilder修改,默认使用Executors.newCachedThreadPool() // Called in a separate thread @Subscribe(threadMode = ThreadMode.ASYNC) public void onMessage(MessageEvent event){ backend.send(event.message); } ``` ## 修改默认实现的配置: EventBus提供了很多配置,一般的情况下我们可以不用配置,但是,如果你有一些其他要求,比如控制日志在开发的时候输出,发布的时候不输出,在开发的时候错误崩溃,而发布的时候不崩溃 修改默认实现的配置,记住,必须在第一次EventBus.getDefault()之前配置,且只能设置一次.建议在application.onCreate()调用 EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).installDefaultEventBus(); ``` // 定制默认的EventBus,addIndex(new GenEventBusIndex())启用加速模式, // 在Application启动的时候就调用这行代码保证之后所有的EventBus都默认使用了加速模式 // addIndex(new GenEventBusIndex())索引加速 // throwSubscriberException(BuildConfig.DEBUG)调试时抛出异常 // logNoSubscriberMessages(true)默认true // logSubscriberExceptions(true)默认true // sendNoSubscriberEvent(false)默认true // sendSubscriberExceptionEvent(false)默认true // eventInheritance(false)指定是否发消息给这个事件的父事件对应的订阅者,默认为true.如果为false,只会发消息给类型完全一致的订阅者 // strictMethodVerification(false)指定是否严格校验,默认为false.严格校验会直接抛出异常 ``` ## priority事件优先级 ``` //priority越大,优先级越大,越早收到消息.备注:优先级只是在相同的ThreadMode中才有效,不同的ThreadMode不起作用 @Subscribe(priority = 1); public void onEvent(MessageEvent event) { } ``` ## 终止事件传递 ``` // 中止事件传递,后续事件不在调用.注意:只能在传递事件的时候调用 @Subscribe public void onEvent(MessageEvent event){ … EventBus.getDefault().cancelEventDelivery(event) ; } ``` ## 混淆 ``` -keepattributes *Annotation* -keepclassmembers class ** { @org.greenrobot.eventbus.Subscribe ; } -keep enum org.greenrobot.eventbus.ThreadMode { *; } -keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent { (java.lang.Throwable); } ```