您的位置:首页 > 移动开发 > Android开发

EventBus的使用

2016-06-20 10:26 417 查看
EventBus的源码地址:https://github.com/greenrobot/EventBus


EventBus in 3 steps

Define events:
public class MessageEvent { /* Additional fields if needed */ }


Prepare subscribers

Register your subscriber (in your onCreate or in a constructor):
eventBus.register(this);


Declare your subscribing method:
@Subscribe

public void onEvent(AnyEventType event) {/* Do something */};


Post events:
eventBus.post(event);


This getting started guide shows these 3 steps in more detail.
EventBus的实例:https://github.com/yanbober/Android-Blog-Source/tree/master/Android-EventBus-Demo
EventBus的源码解析:http://blog.csdn.net/lmj623565791/article/details/40920453

1、onEvent

2、onEventMainThread

3、onEventBackgroundThread

4、onEventAsync

这四种订阅函数都是使用onEvent开头的,它们的功能稍有不同,在介绍不同之前先介绍两个概念:

告知观察者事件发生时通过EventBus.post函数实现,这个过程叫做事件的发布,观察者被告知事件发生叫做事件的接收,是通过下面的订阅函数实现的。

onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread:如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
onEventBackground:如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android