Magren

Magren

Idealist & Garbage maker 🛸
twitter
jike

Using EventBus in Android

These days, I have been thinking about finding a learning path for Android system online, and then I found the Alibaba Android Development Manual on Alibaba Cloud. Although there are already places to download it for free online, I still decided to support it by paying a small amount of money. It's only one yuan, and it also comes with the qualification for an exam certificate. Overall, it's very comfortable.

The website is as follows:

Alibaba Android Development Manual

I guess it's because I have limited exposure to it, I was confused by the first item at the beginning.

  1. [Mandatory] For data communication between activities, if the data size is relatively large, avoid using Intent + Parcelable. You can consider alternative solutions such as EventBus to avoid TransactionTooLargeException.

What is this "EventBus" exactly???

Overview of EventBus#

EventBus is an Android event publishing/subscription framework that simplifies Android event delivery by decoupling publishers and subscribers. Here, events can be understood as messages. Event delivery can be used for communication between the four major components of Android, as well as between asynchronous threads and the main thread, etc.
Traditional event delivery methods include: Handler, BroadcastReceiver, and Interface callbacks. Compared to these methods, EventBus has the advantages of concise code, simple usage, and full decoupling of event publishing and subscription.

Within EventBus, there are three objects:

  • Event: This refers to the message, which can be a general event or a sticky event. The special thing about sticky events is that even if a subscriber subscribes to the event type after the event is published, it can still receive the most recent sticky event of that type.
  • Subscriber: This refers to the object that subscribes to events. When a publisher publishes an event, EventBus will execute the subscriber's event response function. Subscribers subscribe to a certain event type through the register interface and unsubscribe through the unregister interface.
  • Publisher: This refers to the object that publishes events. Events are published through the post interface, and sticky events are published through postSticky.

Github link: EventBus

Usage#

I understand the principles, but I need to know how to use it, otherwise I won't know where to copy and paste it in the future. So I found its usage method online.

General Event#

Custom event class
public class Event {

    String message;


    public Event(String message){
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}
Register in the page that needs to receive messages
EventBus.getDefault().register(this);
Method for receiving messages
@Subscribe(threadMode = ThreadMode.MAIN)
   public void getEvent(Event event) {
       msg = event.getMessage();
       tv.setText(msg);
   }
Send event
@OnClick(R.id.bt_return)
    public void renturnActivity(){
        // Send event
        EventBus.getDefault().post(new Event("Magren"));
        finish();
    }
Unregister when the registered page is destroyed
@Override
    protected void onDestroy() {
        super.onDestroy();
        // Unregister
        EventBus.getDefault().unregister(this);
    }

With the above methods, we can register EventBus events in MainActivity, write the response event method, and when we jump to another Activity and click the button to send an Event event to MainActivity, we will find that our event has been received and displayed when we return to MainActivity.

MainActivity:
eventMain1.png

SendMainActivity:
eventSend.png

Return to MainActivity:
eventMain2.png

This is the usage method for general events, but what I want is to pass data from the current Activity to the next Activity and use it in the next Activity. However, when I tried to implement it using the above method, I found that it didn't work. Later, I realized that I needed to use our sticky events here.

Sticky Event#

Custom event class
public class Event {

    String message;


    public Event(String message){
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}
Register in the page that needs to receive messages
EventBus.getDefault().register(this);
Method for receiving messages

This time, there is an additional "sticky = true" parameter.

@Subscribe(sticky = true,threadMode = ThreadMode.MAIN)
    public void getEvent(Event event) {
        msg = event.getMessage();
        tv.setText(msg);
    }
Send event

Send the message first and then perform the Activity jump. Note that this is postSticky, sending a sticky event.

@OnClick(R.id.bt_return)
   public void renturnActivity(){
       // Send event
       EventBus.getDefault().postSticky(new Event("Magren"));
       Intent intent = new Intent(this,MainActivity.class);
       startActivity(intent);

   }
Unregister when the registered page is destroyed
@Override
    protected void onDestroy() {
        super.onDestroy();
        // Unregister
        EventBus.getDefault().unregister(this);
    }

Now we can directly send events to the next Activity and use them inside.

  1. SendActivity

  2. MainActivity

EventBus Event Thread Handling#

In the annotation @Subscribe(threadMode = ThreadMode.MAIN), we used ThreadMode.MAIN, which means that no matter which thread the event is published from, the onEvent method of the event subscriber will be executed in the UI thread. This is very useful in Android because UI updates can only be done in the UI thread, so methods in this mode cannot perform time-consuming operations.

  • ThreadMode.POSTING: The event subscription function onEvent will run in the same thread as the event was published in. This means that the event publishing and event receiving occur in the same thread. When using this method, time-consuming operations cannot be performed in the onEvent method, as it may cause event distribution delays.
  • ThreadMode.BACKGROUND: If the event is published in the UI thread, the onEvent function of the subscriber will run in a background thread. If the event was originally published in a background thread, the onEvent function will be executed in that same thread.
  • ThreadMode.AYSNC: When using this mode, a new child thread will be created to execute the subscription function, regardless of which thread the event was published from.

Points to Note#

  • Registration should be written in onCreate or onStart, and try to avoid writing it in onResume, as it may cause multiple registrations, which can lead to errors and app crashes.
  • Unregistering should be written in onDestroy, writing it in onStop may cause exceptions, and checking may cause situations where the page exits, so unregister in a timely manner.
  • Before registering, you can check if it has already been registered.
if (!EventBus.getDefault().isRegistered(this)) {
    EventBus.getDefault().register(this);
}
  • If threadMode is not declared, the default thread mode is ThreadMode.POSTING.

The above is a summary of some of the usage of EventBus that I found online, as well as my own practice. Every time I browse the internet, I can discover knowledge points that I don't understand. The road ahead is long.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.