Android-EventBus框架详细介绍与简单实现

788 阅读1分钟

常用事件消息传递

  • 一个实现了监听器接口的类,必须把它自身注册到它想要监听的类中去
  • 使用广播,内部的实现都需要IPC(进程间通信),从传递效率上来讲,可能并不太适合上层的组件间通信
  • Activity间的消息传递便是通过startActivityForResult和onActivityResult,会产生较多的状态或者逻辑判断,而且Intent或者Bundle传值还得监测类型,容易发生错误

EventBus概述

EventBus是一款针对Android优化的发布/订阅事件总线。主要功能是替代Intent,Handler,BroadCast在Fragment,Activity,Service,线程之间传递消息.优点是开销小,代码更优雅。以及将发送者和接收者解耦。

EventBus流程

EventBus基本用法

注册:

EventBus.getDefault().register(this);
EventBus.getDefault().register(this,methodName,Event.class);

取消注册:

@Override 
protected void onDestroy() { 
    super.onDestroy(); 
    EventBus.getDefault().unregister(this);
 }

订阅处理数据:

onEventMainThread,onEvent
onEventPostThread,onEventAsync
onEventBackgroundThread

发布:

EventBus.getDefault().post(new MessageInfo("消息类参数"));

下面写一个小例子:

public class MainActivity extends AppCompatActivity {
    Button btn_first;
    TextView tx_show;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        btn_first = findViewById(R.id.btn_first);
        tx_show = findViewById(R.id.tx_show);
        btn_first.setOnClickListener(v -> startActivity(new Intent(MainActivity.this, SecondActivity.class)));
    }
    
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MyEvent event) {
        String msg = "返回数据:" + event.getMessage();
        tx_show.setText(msg);
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}


public class SecondActivity extends AppCompatActivity {
    Button btn_second;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        btn_second = findViewById(R.id.btn_second);
        btn_second.setOnClickListener(v -> {
            EventBus.getDefault().post(new MyEvent("second acticity is click"));
            finish();
        });
    }
}