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

2020-12-11  本文已影响0人  多仔百事宅
常用事件消息传递
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();
        });
    }
}
上一篇下一篇

猜你喜欢

热点阅读