This is the 21st day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Recently, I had the honor to contact EventBus, a good Android communication framework, which made it much easier to develop in practice. In the past, the communication between the child thread and the main thread, Fragment, and Service needed to be realized through Handler. Now, we just need EventBus to fulfill our requirements easily.

EventBus can be downloaded from github.com/greenrobot/…

An overview,

EventBus is a publish/subscribe message EventBus for Android that simplifies communication between components, making our application simpler and faster to communicate. Let’s look at EventBus’s message passing diagram:

The EventBus main thread consists of four main components:

  • Publisher Publisher: Used to distribute our Event events, distributed via post in EventBus.
  • Subscriber Subscriber: used to receive our events in which we process the data we receive. There are four types of subscription events, all developed as onEvent.
  • Event: Any corresponding can be used as an Event, such as any string, which is the communication carrier between the publisher and the subscriber.
  • EventBus: Acts as a hub for our events to be distributed accordingly.

For example, the EventBus messaging mechanism is the express delivery mechanism in our daily life. If you go to the express site to send the express, you are the event sender, your package is the event, the express site is the EventBus, and the recipient of the express is the event subscriber. The Courier company will load and sort your package and then send it to the recipient, just like EventBus.

Second, Subscriber ThreadMode

Subscriber in EventBus has four subscription functions.

  • OnEvent: If onEvent is used as a subscription function, the onEvent will run in the thread in which the event is published, that is, the event is published and the event is received in the same thread. When you use this method, you cannot perform time-consuming operations in the onEvent method, which would delay event distribution.
  • OnEventMainThread: Using onEventMainThread as the subscription function, the onEventMainThread will be executed in the UI thread regardless of which thread the event was published in, and the receiving event will be run in the UI thread. This is very useful in Android. The onEvnetMainThread method cannot perform time-consuming operations because the new UI can only be created in the UI thread on Android. Otherwise, an ANR exception will occur.
  • OnEventBackground: Using onEventBackgrond as the subscription function, if the event was published in the UI thread, then onEventBackground will run in the child thread, if the event was originally published in the child thread, The onEventBackground function is executed directly in that child thread.
  • OnEventAsync: Using this function as a subscription function, a new child thread will be created to execute onEventAsync no matter which thread the event is published in.

Analyzing the above four threadmodes, we can obviously find that the above four types are designed to solve the communication between our components. For example, we used to start a child thread to download, and then publish messages through Hanlder to update our UI components in the UI thread. ,

2. How to use EventBus

Foreplay: Android Studio user adds:

The compile 'DE. Greenrobot: eventbus: 2.4.0'Copy the code

Eclipse users simply copy the JAR package into the libs directory.

1, define events, we said in front of the event can be any entity object, as long as it can meet the needs of our transfer data, at the same time to guarantee the uniqueness of it, or if there are multiple events to send the same type, will result in our receiver disorder, so usually we are a custom event classes encapsulate our data processing. For example:

public static class EventText{ private String text; public EventText(String text){ this.text = text; } public String getText(){ return this.text; }}Copy the code

We define an EventText event (in plain English, a class) that encapsulates our data.

2, send the event, the event has been defined, we can send the event, to pass our data.

 EventBus.getDefault().post(new EventText(response));
Copy the code

3. Initialize the event subscriber page. Register the event receiving page in EventBus, and unregister the event when the page is destroyed. Normally, we register our Activity in the onCreate() method:

	protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
    }
Copy the code

Unregister in onDestroy() :

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

4, event subscribers for data processing, event carriers of our data sent, now we need to process the event. We’ve already said that there are four ThreadMode event handlers defined in EventBus, so we’ll just do one of the receive handlers as we see fit. Such as:

	public void onEvent(EventText eventText){
        tv_textTextView.setText(eventText.getText());
    }
Copy the code

These are the basic steps to use EventBus. Let’s start with a few general steps:

  • Eventbus.getdefault (). Register (Object subscriber) : registers the EventBus
  • Eventbus.getdefault (). Unregister (Object subscriber) : unregister the EventBus
  • Eventbus.getdefault (). Post (Object event) : event that a message is sent
  • Public void onEvent*****(Object event) : receives messages
  • Eventbus.getdefault ().registersticky (Object subscriber) : sticky EventBus registration. In this case, the message is sent first and then the subscriber is registered. If register is used, the message cannot be received.
  • Eventbus.getdefault (). PostSticky (Object event) : Sends a message when there are no subscribers but expects to receive the message when there are subscribers.

Here’s how to use one in Android Studio. I have written several examples of demo, the renderings are as follows:

In the illustration above, I wrote three demos, one for passing data inside an activity, the second for getting data from another activity, and the third for an activity passing data to another page. In the three demos, they correspond to:

  • The first is that the page acts as the sender and subscriber of the message, all in itself.
  • The second is that the page acts as the subscriber of the event and the other pages act as the event sender
  • The third page serves as the private affair sender and the other pages serve as the event subscribers. If there is a sender before a subscriber, postSticky and registerSticky will be used.

Let’s pick the first demo and show it to you. If you’re interested, you can download the demo.

1. Define our message events to encapsulate the data we pass.

public static class FirstEvent{ private String value; public FirstEvent(String value) { this.value = value; } public String getValue() { return value; }}Copy the code

2, the code is relatively simple, we directly look at the whole page code.

public class FirstActivity extends Activity { private Button btn_showDownLoad; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); setContentView(R.layout.activity_first); btn_showDownLoad = (Button) findViewById(R.id.btn_toast); btn_showDownLoad.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } EventBus. GetDefault (). The post (new EventBusEvents. FirstEvent (" I from the Internet to download the text ")); } }).start(); }}); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } public void onEventMainThread(EventBusEvents.FirstEvent firstEvent){ Toast.makeText(this, firstEvent.getValue(),Toast.LENGTH_SHORT).show(); }}Copy the code

We register the EventBus Event in the onCreate() method, destroy the EventBus Event in the onDestroy() method, click the Button to send the Event, start a child thread emulation, and define our Event receiver function. That’s what simple logic looks like. It’s convenient.

The above example shows that it is much easier to transfer data without using intents. EventBus does provide great convenience in some special cases, but we need to decide according to the situation, otherwise it will lead to too many events, which is not very good.

Source code download address