集成EventBus

作者: 蓝不蓝编程 | 来源:发表于2018-10-19 16:53 被阅读5次

背景:

安卓各模块见经常需要发送消息,以前多采用广播,但是后来有了更优的解决方案:EventBus,传输消息非常方便。下文介绍一下如何集成EventBus。

集成步骤:

1.build.gradle中增加依赖:
implementation 'org.greenrobot:eventbus:3.1.1'
2.注册接收器(Activity的onCreate方法中写)
EventBus.getDefault().register(this);
3.发送事件:
EventBus.getDefault().post( "发射了一个事件");
4.接收事件(在Activity或Fragment中写)

/**
     *  自定义一个方法 接收事件,方法名字可以随便写。
     *  发送的数据类型可以自行定义,一般项目中为了区分不同的消息,会定义一个基类,
     *  然后派生出不同的事件子类。可以参考SecondActivity.java
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String event) {
        Toast.makeText(this, event, Toast.LENGTH_SHORT).show();
    }

5.取消注册

@Override
    protected void onDestroy() {
        super.onDestroy();
        //取消注册 , 防止Activity内存泄漏
        EventBus.getDefault().unregister(this);
    }

Demo源代码:

https://gitee.com/cxyzy1/eventBusDemo/

参考资料:

https://www.cnblogs.com/zhaoyanjun/p/6039221.html

安卓开发技术分享: https://www.jianshu.com/p/442339952f26

相关文章

网友评论

    本文标题:集成EventBus

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