EventBus

作者: 啤酒小龙虾 | 来源:发表于2018-05-17 10:42 被阅读0次

EventBus是Android下高效的发布/订阅事件总线机制。

官网:https://github.com/greenrobot/EventBus

添加依赖:

//EventBus

compile'org.greenrobot:eventbus:3.0.0'

EventBus基本使用

1、定义一个事件类

public class TestEvent {

    public Stringmsg;

}

2、注册,注销 ,实现订阅方法 (只有接收方才注册,发布方不用注册 直接发消息就行)

// 注册一个订阅者

EventBus.getDefault().register(this);

// 注销订阅者

EventBus.getDefault().unregister(this);

// 实现订阅的方法   注意注解的添加   方法名可以随便起

@Subscribe(threadMode = ThreadMode.MAIN)

public void onEvent(TestEvent event) {

  Toast.makeText(this, "receive event ===" +  event.msg,Toast.LENGTH_SHORT).show();

}

3、发布消息

// 定义事件

TestEvent event = new TestEvent();

event.msg = "我是来自TestEvent的消息";

// 发布事件

EventBus.getDefault().post(event);

相关文章

网友评论

      本文标题:EventBus

      本文链接:https://www.haomeiwen.com/subject/uxgvdftx.html