Android EventBus使用详解

来源:互联网 发布:三维立体制作软件 编辑:程序博客网 时间:2024/05/17 23:17

一、概述

EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦
1、添加gradle依赖
compile 'org.greenrobot:eventbus:3.0.0'
2、接收消息的页面注册
//注册EventBusEventBus.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、接收消息
订阅发布可在不同线程,不可做耗时操作
@Subscribepublic void onEventMainThread(final FirstEvent event) {    Log.d("best", "onEventMainThread收到了消息:" + event.getAppDevice().getDeviceMac());}
//同一线程订阅发布,不可做延时操作@Subscribepublic void onEvent(final FirstEvent event) {
    Log.d("best", "onEvent收到了消息:" + event.getAppDevice().getDeviceMac());}
//如果UI线程发布,则在子线程执行,如果是在子线程执行,则直接在子线程执行@Subscribepublic 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);


1 0