Use EventBus event publish/subscribe framework to implement event delivery in Android

Scenes

EventBus

EventBus is an event publish-subscribe bus for Android. It simplifies the complexity of communication between various components in the application, especially the problem of communication between fragments, and can avoid many inconveniences caused by the use of broadcast communication.

Official document

https://greenrobot.org/eventbus/documentation/

scenes to be used

When doing projects, it is often necessary to communicate between various components in the application, and between components and background threads. For example, time-consuming operations. After the time-consuming operations are completed, the results are notified to the UI through Handler or Broadcast. N Activities need to communicate through Listener. Another example is the callback method that will be introduced in this article to display the message in the callback method that receives the MQTT push. In the system notification bar, these can be easily implemented through EventBus. EventBus manages the event bus through publish/subscribe (publish/subscribe).

Three roles

Event: Event, it can be of any type, EventBus will make a global notification according to the event type.
Subscriber: Event subscribers. Before EventBus 3.0, we must define the methods starting with onEvent, which are onEvent, onEventMainThread, onEventBackgroundThread, and onEventAsync. After 3.0, the name of the event processing method can be taken at will, but it needs to be annotated. @subscribe, and specify the thread model, the default is POSTING.
Publisher: The publisher of the event, which can publish the event in any thread. Generally, you can get an EventBus object by using EventBus.getDefault(), and then call the post(Object) method.

Four threading models

POSTING: By default, it means that the thread of the event processing function is in the same thread as the thread that publishes the event.
MAIN: Indicates that the thread of the event processing function is in the main thread (UI) thread, so time-consuming operations cannot be performed here.
BACKGROUND: Indicates that the thread of the event processing function is in the background thread, so UI operations cannot be performed. If the thread that publishes the event is the main thread (UI thread), the event processing function will start a background thread. If the thread that publishes the event is a background thread, the event processing function uses this thread.
ASYNC: It means that no matter which thread the event is published, the event processing function will always create a new child thread to run, and UI operations cannot be performed either.

Note:

Blog:
https://blog.csdn.net/badao_liumang_qizhi
Follow the public
account Domineering
programmers Get programming-related e-books, tutorial pushes and free downloads.

achieve

Quick start documentation given on the official website

https://greenrobot.org/eventbus/documentation/how-to-get-started/

 

Here we take the callback method after receiving the message from the MQTT server to pass it to the main thread to display the notification message in the notification bar as an example

StickyEvents sticky events of EventBus are also used here

StickyEvents

What is a sticky event? Simply put, you can receive the event by subscribing to the event after sending the event, similar to sticky broadcast.

Official documents:

https://greenrobot.org/eventbus/documentation/configuration/sticky-events/

Literal translation:

Some events will carry some interesting information after the event is released. For example, an event indicates that a certain initialization has been completed. Or you have some sensor or location data and you want to keep the most recent value. You can use sticky events instead of implementing your own caching. EventBus saves the last sticky event of a specific type in memory. Then, sticky events can be delivered to subscribers or explicit queries. Therefore, you do not need any special logic to consider the data that is already available.

Use EventBus

Introduce dependencies in build.gradle

    //Event bus用来传递消息
    implementation 'org.greenrobot:eventbus:3.0.0'

Then follow the quick start instructions of the official document to create a new message event entity MessageEvent

public class MessageEvent {
    private String message;

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

Then register the event and process the event where you need to subscribe to the event, here is to display the message in the notification bar in MainActivity, so in the onCreate method of MainActivity

        //在需要订阅事件的地方注册事件
        EventBus.getDefault().register(this);

Then you need to handle the event in MainActivity

    //处理事件
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void showTheEventMessage(MessageEvent messageEvent) {
        Log.i(TAG, "showTheEventMessage: show notification");
        showNotification(this, messageEvent.getMessage());
    }

That is, the operation of displaying the notification bar message is performed.

Then in the callback method of receiving the MQTT message

EventBus.getDefault().postSticky(new MessageEvent(msg));

Publish a message, where msg is the string content of the delivered message

The above complete implementation process

Connect to the MQTT server in Android to subscribe to topics and receive push notifications to be displayed in the notification bar (code download attached):

https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/112466469

 

 

 

Guess you like

Origin blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/112476228