EventBus的使用

Posted by 程序亦非猿 on 2015-09-18

EventBus

Android optimized event bus that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.

优化的事件总线,简化app各个类之间的交互.

使用

添加依赖

compile 'de.greenrobot:eventbus:2.4.0'

注意混淆

使用EventBus,如果混淆的话必须要加上以下几句:

1
2
3
4
-keepclassmembers class ** {
public void onEvent*(**);
public void onEventMainThread(**);
}

必备插件

当定义的Event越来越多,我们要寻找某个Event哪里接收哪里发送会比较麻烦.
幸好有这么一个插件可以帮助我们:

EventBus Intellij Plugin

功能:

Provides actions which allow you quickly move around the event bus.

  1. EventBus.post to onEvent or onEventMainThread
  2. onEvent or onEventMainThread to EventBus.post

效果:

onEventMainThread效果图

点击上图的图标,会帮你找到发送的地方.
点击后效果

同样,也能在发送的地方查找哪里接收.

源码解析

EventBus-源码解析