Android自助餐之EventBus框架

Android自助餐之EventBus框架

查看全套目录

下载完整源代码

配置build.grandle

compile 'de.greenrobot:eventbus:2.4.0'

实例化EventBus

eventBus=EventBus.builder().build();

注册事件监听

eventBus.register(this);
this为事件接收者(消费事件、处理事件…随便怎么说吧)

定义被传递的事件类

注意要定义一个,这个类可以随便定义,也可以用现有的类

class Event{
    public String result="default";
}

发送事件

eventBus.post(event);
可以再任意线程任意位置发送事件,但要保证eventBus在注册和发送时为同一个对象。

处理时间

在注册时的this的类中写如下方法
- public void onEventMainThread(Event event){}
接到事件后在主线程消费事件
- public void onEvent(Event event){}
接到事件后在事件post的线程中消费事件(注意不能进行耗时操作,否则影响事件传递)
- public void onEventBackgroundThread(Event event){}
在后台线程中消费事件。如果事件的post线程为后台线程,则使用post线程,否则在新的子线程中消费事件
- public void onEventAsync(Event event){}
在新的子线程中消费事件

发布了69 篇原创文章 · 获赞 55 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/xmh19936688/article/details/51510309