EventBus的粗暴使用方法

既然是简单粗暴,就不写什么EventBus详细介绍了,这里有源码详解和具体使用方法https://www.jianshu.com/p/6da03454f75a

首先:

1、添加依赖。

1 implementation 'org.greenrobot:eventbus:3.0.0'

2、定义一个消息事件类;

/**
 * 传递消息时使用,可以自己增加更多的参数,不限制类型
 */

public class EventMsg {

    private String Tag;
    private String Msg;


    public String getTag() {
        return Tag;
    }

    public String getMsg() { return Msg; }

    public void setTag(String tag) {
        Tag = tag;
    }
    public void setMsg(String msg){
        Msg = msg;
    }
}

3、注册EventBus,在软件初始化时注册

1 /*register EventBus*/
2         if (!EventBus.getDefault().isRegistered(this)) {
3             EventBus.getDefault().register(this);
4         }

4、发送消息。

 1 /**
 2      * 发送连接状态消息
 3      *
 4      * @param constants
 5      */
 6     private void sendEventMsg(String msg) {
 7         EventMsg msg = new EventMsg();
 8         msg.setTag(msg);
 9         EventBus.getDefault().post(msg);
10     }

5、接收消息;

1 @Subscribe(threadMode = ThreadMode.MAIN)
2     public void skipToMainActivity(EventMsg msg) {
3     //在这里通过msg读取    
4     msg.getTag();
5 }
6     

猜你喜欢

转载自www.cnblogs.com/bbqopdd/p/10884867.html
今日推荐