Eventbus 3.0的简单实用

时间:2019-01-09
本文章向大家介绍Eventbus 3.0的简单实用,主要包括Eventbus 3.0的简单实用使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、介绍

项目开发的时候经常使用到应用程序的各组件间或组件与后台线程间进行通信,例如:在子线程中进行请求数据,当数据请求完毕后通过Handler或者是广播通知UI,Fragment之间可以通过Listener进行通信等。当工程越来越大的时候,继续使用Intent、Handler、Broadcast进行模块间通信时代码量大,而且高度耦合。不利于项目的后期迭代,eventBus 就很好的解决了这个问题。

2、关于Eventbus的详细介绍,大家可以去官网http://greenrobot.org/eventbus/详细了解。

3、关于EventBus的概述

出发事件可以是任意类型。
在EventBus3.0之前必须定义以onEvent开头的几个方法,分别是onEvent、onEventMainThread、onEventBackgroundThread和onEventAsync,一般都使用onEventMainThread;在3.0之后事件处理的方法名可以随意取,需要在方法名上加上注解@subscribe(),并且指定线程模型,默认是POSTING。
我们可以在任意线程里发布事件,一般情况下,使用EventBus.getDefault()就可以得到一个EventBus对象,然后再调用post(Object)方法即可。

4、EventBus的简单使用

(1)在module的build.gradle引用库

implementation 'org.greenrobot:eventbus:3.0.0'

(2)新建一个类,用于消息传递的Event类

//例:
public class ShareUserEvb {
    private String userName;
    private String userId;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
}

(3)在要接收消息的页面注册Eventbus:(一般是在Activity的onCreate()方法或者是Fragment的onActivityCreated()里写)

EventBus.getDefault().register(this); 

(4)在要接收消息的页面销毁的时候解绑(很重要)一般在onDestroy()里写

//fragment里的解绑位置
@Override
    public void onDestroyView() {
        super.onDestroyView();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);
    }

(5)如何获取传过来的值呢?

@Subscribe
    public void onEventMainThread(ShareUserEvb event) {
       String message = event.getUserId();
    }

(6)在需要传值的页面进行传值

//其实这一句就可以了,我这里是测试
ShareUserEvb event = new ShareUserEvb();
event.setUserId("111");
//post就是把消息发送出去
EventBus.getDefault().post(event);

到这里就结束啦:附上eventbus源码地址https://github.com/greenrobot/EventBus

参考博客:
1.https://www.jianshu.com/p/f9ae5691e1bb