Common event messaging

  • A class that implements a listener interface must register itself with the class it wants to listen on
  • With broadcasting, internal implementations require IPC (inter-process communication), which may not be well suited for upper-level inter-component communication in terms of delivery efficiency
  • The message passing between activities is via startActivityForResult and onActivityResult, which generates a lot of state or logical decisions. In addition, the Intent or Bundle must monitor the type of value passed, which is prone to errors

EventBus overview

EventBus is an android-optimized publish/subscribe EventBus. The main function is to replace Intent,Handler,BroadCast messages between fragments, activities, services, and threads. The advantages are lower overhead and more elegant code. And decouple the sender from the receiver.

EventBus process

Basic usage of EventBus

Registration:

EventBus. GetDefault (). The register (this); EventBus. GetDefault (). The register (this, methodName, Event. Class);Copy the code

Cancel registration:

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

Subscription processing data:

OnEventMainThread, onEvent onEventPostThread, onEventAsync onEventBackgroundThreadCopy the code

Release:

Eventbus.getdefault ().post(new MessageInfo(" message class parameter "));Copy the code

Here is a small example:

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 = "return data :" + 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(); }); }}Copy the code