EventBus事件分发

来源:互联网 发布:java面向对象经典题目 编辑:程序博客网 时间:2024/06/05 05:34

1. libs下加入架包

2. 定义一个事件参数传递类

package com.choice.zlc.ottodemo;/** * Created by zlc on 2016/10/27. * 参数传递事件类 */public class TestEvent {    private String s;    public TestEvent(String s){        this.s = s;    }    public String getS() {        return s;    }}

3. Activity中实现

  1. MainActivity中实现
订阅事件 @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        EventBus.getDefault().register(this);  //订阅事件        initView();    } 取消订阅@Override    protected void onDestroy() {        super.onDestroy();        EventBus.getDefault().unregister(this);    }事件处理 更新ui 接收数据 public void onEventMainThread(TestEvent event){       mText.setText(event.getS()+""); }
  1. SecondActivity中实现
     mBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                EventBus.getDefault().post(new TestEvent("我是第二个页面传递过来的数据"));   //发布事件                finish();            }        });

4. 常用方法

register(Object o):注册,注册以后可以订阅事件unregister(Object o)注销.放弃对之前的订阅的所有事件post(Object o)发布事件onEventMainThread(Params p)  //运行在主线程onEvent(Params p)  //如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。onEventBackgroundThread(Params p)  //如果当前非UI线程,则直接调用;如果是UI线程,则将任务加入到后台的一个队列,最终由Eventbus中的一个线程池去调用onEventAsync(Params p)      //使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行

6. 联系方式

QQ:1509815887
email:zlc921022@163.com

0 0
原创粉丝点击