1、在onStart()方法中注册

@Override
    public void onStart() {
        super.onStart();
        // 注册 EventBus
        // 判断 Eventbus 是否注册
        if (!EventBus.getDefault().isRegistered(this)) {
        EventBus.getDefault().register(this);
        }
    }

2、在onStop()方法中销毁

@Override
    public void onStop() {
        super.onStop();
        // 注销操作
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

3、发送消息

EventBus.getDefault().post(new EventBusMsgInfo(position));

4、自定义方法 接受发送的数据

@Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventBusMsg(EventBusMsgInfo busMsgInfo){
        // 调用切换界面的方法,实现切换界面
        //该方法可直接将传递过来的数据进行操作
        switchPager(busMsgInfo.position);
    }
    定义发送消息传递的bean类
    public class EventBusMsgInfo {
    
        public int position;
    
        public EventBusMsgInfo(int position) {
            super();
            this.position = position;
        }
        
    }

5、重点提示

  5.1、添加注解在此处有三种模式
            模式一:POSTING:默认的模式,发送和接受操作都在一个线程中执行
            模式二:MAIN:不管在那个线程发送消息,都在UI线程接收
            模式三:BACKGROUND:如果在子线程发送消息,那么接收也必须在子线程,如果在主线程发送消息,那么接收也必须在主线程。
            模式四:ASYNC:接收和发送都在子线程中执行
     5.2、EventBus发送消息 发送的对象应该是一个bean类本例中

posted on 2017-01-11 18:55  从前有個人  阅读(1094)  评论(0编辑  收藏  举报