Welcome to Ray's Blog

Stay Hungry Stay Foolish - Steve Jobs

0%

Android EventBus笔记


概述

定义:一个发布/订阅的事件总线框架。
包含:

  • 发布者poster
  • 订阅者subscriber
  • 事件event
  • 总线thread

EventBus 角色关系如图所示:

示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class EventBusActivity extends AppCompatActivity {

@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_bus);
//在onCreate()方法中注册
EventBus.getDefault().register(this);
}

/**
* 同线程接收Event事件
* @param param
*/
public void onEvent(Object param) {

}

/**
* 主线程接收Event事件处理
* @param param
*/
public void onEventMainThread(Object param){

}

/**
* 子线程接收Event事件处理
* @param param
*/
public void onEventPostThread(Object param){

}

/**
* 后台接收Event事件处理
* @param param
*/
public void onEventBackgroundThread(Object param){

}

/**
* 异步接收Event事件处理
* @param param
*/
public void onEventAsync(Object param){

}

@Override protected void onDestroy() {
//在onDestory()方法中注销EventBus
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}

** EventBus.getDefault().register(this);**
作用:扫描了当前类的所有方法,把匹配的方法最终保存在subscriptionByEventType(Map(key:eventType,value:CopyOnWriteArrayList<Subscription>))中。其中eventType是我们方法参数的 class,Subscription 中则保存着subscriber,subscriberMethod(method,threadMode,eventType,),priority;(subscripber:即我们订阅Event的类Activity)
onEventXXX:决定当前的方法最终运行在上面线程和怎么运行。

** EventBus.getDefault().post(param); **
作用:将参数 param 发布出去,EventBus 会在它内部存储的方法中,进行扫描,找到参数匹配的,就使用反射进行调用。

** EventBus.getDefault().unregister(this);**
作用:反注册 EventBus 的监听。

总结

通俗的解释原理就是:EventBus 在其内部存储了一堆定义的以 onEvent 开头的带参数方法,然后调用post(param)的时候,格局 post 传入的参数,去找到匹配的方法,然后通过反射区调用该方法。

参考资源