Android EventBus使用详解

一、概述

EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦
1、添加gradle依赖
compile 'org.greenrobot:eventbus:3.0.0'
2、接收消息的页面注册
//注册EventBus
EventBus.getDefault().register(this);
3、新建空类主要用来传递消息,也可以传递实体类
public class FirstEvent {
    private AppScene appScene;
    private AppDevice appDevice;
    public FirstEvent(AppScene appScene) {
        this.appScene = appScene;
    }
    public FirstEvent(AppDevice appDevice){
        this.appDevice = appDevice;
    }

    public AppScene getAppScene(){
        return appScene;
    }

    public AppDevice getAppDevice(){
        return appDevice;
    }
}
 
 
4、发送消息
EventBus.getDefault().post(new FirstEvent(appDeviceInfo));

5、接收消息
订阅发布可在不同线程,不可做耗时操作
@Subscribe
public void onEventMainThread(final FirstEvent event) {
    Log.d("best", "onEventMainThread收到了消息:" + event.getAppDevice().getDeviceMac());
}

//同一线程订阅发布,不可做延时操作
@Subscribe
public void onEvent(final FirstEvent event) {
    Log.d("best", "onEvent收到了消息:" + event.getAppDevice().getDeviceMac());
}
//如果UI线程发布,则在子线程执行,如果是在子线程执行,则直接在子线程执行
@Subscribe
public void onEventBackground(final FirstEvent event) {
    Log.d("best", "onEventBackground收到了消息:" + event.getAppDevice().getDeviceMac());
}
//无论在哪个线程发布,都会创建新的子线程运行
onEventAsync

@Subscribepublic void onEventAsync(final FirstEvent event) { Log.d("best", "onEventAsync收到了消息:" + event.getAppDevice().getDeviceMac());}

6、解除注册
EventBus.getDefault().unregister(this);

 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值