EventBus简介

一、概述

EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。

1、下载EventBus的类库
源码:https://github.com/greenrobot/EventBus

2、基本使用

(1)自定义一个类,可以是空类,比如:

    public class AnyEventType {  
         public AnyEventType(){}  
     }  


(2)在要接收消息的页面注册:

    eventBus.register(this);  

(3)发送消息

    eventBus.post(new AnyEventType event);  

(4)接受消息的页面实现(共有四个函数,各功能不同,这是其中之一,可以选择性的实现,这里先实现一个):


    public void onEvent(AnyEventType event) {}  


(5)解除注册

  
eventBus.unregister(this); 

EventBus有几个不同的接收函数

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.
上面列出的这四个函数,关键问题在于,我们怎么指定调用哪个函数呢?

当发过来一个消息的时候,EventBus怎么知道要调哪个函数,就看哪个函数传进去的参数是这个类的实例,哪个是就调哪个。那如果有两个是呢,那两个都会被调用!!!!


    public void onEventMainThread(FirstEvent event) {  
      
        Log.d("harvic", "onEventMainThread收到了消息:" + event.getMsg());  
    }  
      
    public void onEventMainThread(SecondEvent event) {  
      
        Log.d("harvic", "onEventMainThread收到了消息:" + event.getMsg());  
    }  
      
    public void onEvent(ThirdEvent event) {  
        Log.d("harvic", "OnEvent收到了消息:" + event.getMsg());  
    }  

使用两个onEventMainThread分别接收FirstEvent实例的消息( EventBus.getDefault().post(new FirstEvent("FirstEvent btn clicked"));)和SecondEvent实例的消息( EventBus.getDefault().post(new SecondEvent ("SecondEvent btn clicked"));),使用onEvent接收ThirdEvent实例的消息( EventBus.getDefault().post(new ThirdEvent("SecondEvent btn clicked"));)。


参考文章:

       http://blog.youkuaiyun.com/harvic880925/article/details/40660137

        http://blog.youkuaiyun.com/harvic880925/article/details/40787203


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值