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     

接受消息有四个函数:

 

1 public void onEvent(AnyEventType event) {} 
2 public void onEventMainThread(AnyEventType event) {} 
3 public void onEventBackgroundThread(AnyEventType event) {} 
4 public void onEventAsync(AnyEventType event) {} 

 

 

 

onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。
onEventMainThread:如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。
onEventBackground:如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。
onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync. 

 

6、解除注册

1 EventBus.getDefault().unregister(this);

 

posted @ 2019-05-18 10:25  bbqopdd  阅读(370)  评论(0编辑  收藏  举报