Youth is not the end of an age, nor is it a wizened face, but always have the sprint dream mood and the courage to challenge.
An overview,
EventBus is a publish/subscribe EventBus for Android and Java. The main function is to replace Intent, Handler, and BroadCast to transmit messages between activities, fragments, and Service threads. EventBus simplifies communication between application components, decouples (effectively separates) event senders and receivers, and avoids complex and error-prone dependency and lifecycle issues with less overhead and more elegant code.
The communication between Andorid components may be realized by the Handler message mechanism or broadcast mechanism, but they have a large amount of code and are easy to produce coupling on the components. Why use EventBus for communication?
Let’s take a look at the benefits of EventBus:
- 1. Simplify the communication between components;
- 2. Decouple the event communication parties;
- 3. Easy to use in activities, fragments and background threads;
- 4. Avoid complex and error-prone dependency and lifecycle issues;
- 5, flexible and convenient to specify the working thread and priority;
- 6, fast speed, good performance, simple and elegant code;
- 7. The library is relatively small and does not occupy memory.
EventBus uses the publish/subscriber model:
Publishers publish events through EventBus, subscribers subscribe to events through EventBus, and when the publisher sends an event, the event handling methods of subscribers to the event are called. As you can see from the figure, when a publisher sends an event, the event is delivered simultaneously to one or more subscribers of the event.
1. What is the publish/subscriber model?
Subscriber registers the Event they want to subscribe to EventBus. When Publisher publishes the Event to EventBus, that is, when the Event is triggered, The processing code (onEvent()) that subscribers register with the dispatch center is unified by the dispatch center. (Publisher/subscriber mode is not exactly the same as observer mode)
2. Three elements of EventBus
- Event: an Event that can be of any type;
- Publisher:Event publishers, which can publish events in any thread, generally pass
EventBus.getDefault()
Obtain the EventBus instancepost(Object event)
Release event; - The Subscriber:Event subscriber. Prior to EventBus3.0, the subscriber’s event handler must define a concrete method name beginning with onEvent. After 3.0, the method name is optional, but must be added
@Subscribe()
Annotation, and specify thread mode, default isThreadMode.POSTING
.
2. Procedure of using events
(1) Define the event object
The event object can be any Java type, with no special requirements, such as String, int, custom class, etc.
public class MessageEvent {
public String name;
}
Copy the code
(2) Register the event on the page that receives the message
EventBus.getDefault().register(this);
Copy the code
- register(Object subscriber): EventBus Method of subscribing to events, passed
EventBus.getDefault()
Get an event bus instance; The subscriber parameter is the subscriber, which has a method for handling events and must be added@Subscribe
Annotation.
A message is received only if a subscription event is registered. Note: Events are usually registered and deregistered based on the Activity and Fragment lifecycle.
(3) Subscribers implement event handling methods
Also known as the “subscriber method,” this method is called when the corresponding event type is published (on the page receiving the message).
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent message){
//TODO does something after receiving the event
}
Copy the code
- @SUBSCRIBE: The @SUBSCRIBE annotation must be used to define the subscriber method, otherwise the event handling method will not take effect.
- ThreadMode: Specifies the thread in which the method is executed. Threadmode. MAIN specifies the MAIN thread in which the method is executed. (Other modes explained in the next article)
- onMessageEvent(MessageEvent message): Method name of the event handler method,
onMessageEvent()
Is any legal method name, which developers can define themselves; The parameter type MessageEvent is the type of the object that defines the received event. It must be consistent with the type of the published event; otherwise, the event cannot be received.
(4) Release events
EventBus.getDefault().post(Object event);
Copy the code
- Object event (POST) : method used by EventBus to send events. Event is an event Object of any type. The type of the event sent must be the same as that of the event received.
All registered events that currently match the event type are received.
(5) Deregister (deregister) event on the page receiving the message
EventBus.getDefault().unregister(this);
Copy the code
- Unregister (Object subscriber) : this method is used to cancel events for subscribers. If events are no longer needed, this method must be called to cancel events.
Unlog the event when the message page does not exist or is no longer needed.
Iii. Actual combat of the project
1. Common use
For example, register an event in OneActivity and implement event handling, click the button to jump to TwoActivity, click the TwoActivity “Send event” button to send an event to OneActivity, OneActivity toasts after receiving the event information and displays the received data on the screen.
To achieve this effect, we follow the following steps:
Build. Gradle = build. Gradle = build.
Add EventBus3.2 dependencies:
implementation 'org. Greenrobot: eventbus: 3.2.0'
Copy the code
(2) Define event objects
The event Object can be any Java type (Object), no special requirements, such as String, int, custom class, etc. Developers can choose according to the requirements. Here we define a class MessageEvent:
public class MessageEvent {
public MessageEvent(String name) {
this.name = name;
}
public String name;
}
Copy the code
This class is very simple, just defines a single parameter name, which is constructed by passing in a string. It is the wrapper class that carries the parameters of the event object we send the event to, which is also received by the following subscriber method with MessageEvent as the receive type. The two types must be consistent in order to receive the outgoing data successfully.
(3) Register and unregister events on the page that receives the message
As you can see from the above, we receive event messages in OneActivity, so we need to register and unregister events in OneActivity, usually based on the Activity and Fragment lifecycle. So we register the event in our Activity’s onCreate() method and unregister the event in onDestroy() :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
}
@Override
protected void onDestroy(a) {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
Copy the code
Published events are received only if the message page exists and a subscription event is registered. Unlog the event when the message page does not exist or is no longer needed.
Note: Published events cannot be received if the message page does not exist or the page has been destroyed. So before publishing an event, you need to make sure that the page that receives the message has been created and registered for the event. In addition, sticky events allow you to publish events first and then register them later, which allows you to receive events as well, as explained below.
(4) Subscriber’s method of realizing event processing
The method required to implement event handling on the message page OneActivity, also known as the “subscriber method,” is called when the corresponding event type is published and receives a message for the event. Define a method onMessageEvent() to receive the event, set the received data to the mTv_content control, and toast the display.
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent message) {
//TODO does something after receiving the event
mTv_content.setText("onMessageEvent:" + message.name);
Toast.makeText(this."onMessageEvent:" + message.name, Toast.LENGTH_SHORT).show();
}
Copy the code
You must use the @subscribe () annotation to define the subscriber method and declare the threadMode threadMode in it. In this case, to receive data in the MAIN thread threadmode.main, the method name onMessageEvent() is any legal method name that the developer can define. Parameter Type MessageEvent indicates the type of the object that defines the event. It must be the same as the type of the event published. Otherwise, the event cannot be received.
(5) Release events
The sending event is implemented in TwoActivity. The event is published via the Psot() method in EventBus, and the parameter is the custom MessageEvent above. The data carried can be written to the MessageEvent, where the object type is the same as that of the received event.
EventBus.getDefault().post(new MessageEvent("Received the event from TwoActivity."));
Copy the code
So the whole process is complete, isn’t it easy? Here are two Activity codes, the other code is not posted.
The receiving message page: oneactivity.java
/** * Register and receive normal events */
public class OneActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
findViewById(R.id.btn_skip).setOnClickListener(this);
mTv_content = findViewById(R.id.tv_content);
//1. Register event
EventBus.getDefault().register(this);
}
//3. Receive event processing
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent message) {
//TODO does something after receiving the event
mTv_content.setText("onMessageEvent:" + message.name);
Toast.makeText(this."onMessageEvent:" + message.name, Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_skip:// Jump to TwoActivity
startActivity(new Intent(this, TwoActivity.class));
break; }}@Override
protected void onDestroy(a) {
super.onDestroy();
//2. Anti-registration event
EventBus.getDefault().unregister(this); }}Copy the code
Send message page: twoActivity.java
/** * Publish normal events */
public class TwoActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
findViewById(R.id.btn_send).setOnClickListener(this);
mTv_content = findViewById(R.id.tv_content);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:// Publish events
mTv_content.setText("Publish events to OneActivity");
//4. Publish common events
EventBus.getDefault().post(new MessageEvent("Received the event from TwoActivity."));
break;
default:
break; }}}Copy the code
2. Use of sticky events
In the normal event above, subscribers need to register before they can receive published events; That is, the page receiving the message has not yet been created or registered as a subscriber, so the method that handles the event cannot receive the event published by the sender.
EventBus provides a sticky event that can be subscribed to or received after an event is sent. Unlike normal events, which are registered before publishing, sticky events can be published before registering.
For example, in a project, you can send events from Activity1 to Activity2 for event processing. If Activity2 is not created, you cannot receive messages because the EventBus for Activity2 to receive messages has not been registered, and even if events are published, subscribers have not been generated. So I can’t pick it up.
Sticky events are used in much the same way as normal events, except for the way they are published and handled:
(1) The event function processing method of sticky events needs to be added in annotationssticky = true
Flag indicating that the event is a sticky event:
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onStickyEvent(MessageEvent message) {
//TODO does something after receiving the event
}
Copy the code
(2) UsepostSticky()
Publishing sticky events:
EventBus.getDefault().postSticky(Object event);
Copy the code
Sticky events will always exist on EventBus after they are published. They need to be removed when they are not needed. The following methods can be used to remove sticky events:
// Remove the specified stickiness event
removeStickyEvent(Object event);
// Removes stickiness events for the specified object type
removeStickyEvent(Class<T> eventType);
// Remove all sticky events
removeAllStickyEvents();
Copy the code
So for example, let’s create two activities, publish sticky events to StickyReceiveActivity in StickySendActivity, and then jump to StickyReceiveActivity, StickyReceiveActivity Creates and registers an EventBus and subscribes to sticky events.
/** * publish sticky events */
public class StickySendActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sticky_send);
findViewById(R.id.btn_send).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:// Publish events
//4. Publish sticky events
EventBus.getDefault().postSticky("StickySendActivity sends sticky events.");
startActivity(new Intent(this, StickyReceiveActivity.class));
break; }}}Copy the code
Click the Send Sticky Event button to publish sticky events to the StickyReceiveActivity. After publishing sticky events, the system switches to the StickyReceiveActivity.
/** * Register and receive sticky events */
public class StickyReceiveActivity extends AppCompatActivity{
private TextView mTv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sticky_receive);
mTv_content = findViewById(R.id.tv_content);
//1. Register event
EventBus.getDefault().register(this);
}
//3. Receive StickySendActivity, sticky = true indicates sticky event
@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
public void onStickyEvent(String str) {
//TODO does something after receiving the event
mTv_content.setText("OnStickyEvent: received" + str);
Toast.makeText(this."OnStickyEvent: received" + str, Toast.LENGTH_SHORT).show();
EventBus.getDefault().removeStickyEvent(this)// Remove sticky events
}
@Override
protected void onDestroy(a) {
super.onDestroy();
//2. Anti-registration event
EventBus.getDefault().unregister(this); }}Copy the code
StickyReceiveActivity creates and registers an EventBus, subscribed to the sticky event handling method, received the sticky event data, displayed on the mTv_content control, and then removed the current sticky event using removeStickyEvent(this). The effect is as follows:
As you can see, sending sticky events first and then registering to handle events can also receive events.
Note: The parameter type of the event sent must be the same as the parameter type of the event received; otherwise, the event cannot be received.
Several thread modes of EventBus
EventBus provides several threading modes, primarily for thread switching between publishing events and processing events.
The threaded | meaning | The characteristics of |
---|---|---|
1, POSTING | Default thread, indicating that the subscriber will be invoked in the same thread that publishes the event | It is suitable for simple tasks that can be completed in a short time without the main thread, avoiding thread switching and reducing overhead |
2, the MAIN | Indicates that in Android, the subscriber is called in the Android main thread | If the thread issuing the event is the main thread, the subscriber’s event handler will be called directly. If the thread issuing the event is not the main thread, the event is queued to the main thread for execution. So you can’t do time-consuming operations here, and you don’t block the main thread |
3, MAIN_ORDERED | Indicates that in Android, the subscriber is called in the Android main thread | Unlike MAIN, events are sent to the MAIN thread regardless of the thread on which they are published. The queue is always queued for delivery. Be careful not to block the main thread |
4, BACKGROUND | Means that in Android, the subscriber is called in a background thread, | In Android, if the publishing thread is not the main thread, the subscriber’s event handler directly uses that thread. If the publishing thread is the main thread, the event handler starts a background thread and dispatches events in order. Note that the background thread is not blocked. If not on Android, always use a background thread |
5, ASYNC | Does the subscriber create a new child thread to execute no matter what the publishing thread is | EventBus uses a thread pool to efficiently reuse threads that have completed asynchronous operations |
The MAIN and MAIN_ORDERED subscriber processing threads are the MAIN thread, while the BACKGROUND and ASYNC subscriber processing threads are the BACKGROUND thread.
1. Several thread modes are used
To verify which thread handles events in different thread modes, create two activities, ModeReceiveActivity, register EventBus and implement subscriber event handlers. ModeSendActivity is responsible for publishing events.
/** * Several thread modes * register and receive events */
public class ModeReceiveActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "ModeReceiveActivity";
private TextView mTv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mode_receive);
findViewById(R.id.btn_skip).setOnClickListener(this);
mTv_content = findViewById(R.id.tv_content);
//1. Register event
EventBus.getDefault().register(this);
}
//3. Subscriber's receive event handler
// The processing thread is the same as the publishing thread
@Subscribe(threadMode = ThreadMode.POSTING)
public void onMessageEventPosting(String str) {
//TODO does something after receiving the event
mTv_content.setText("onMessageEvent:" + str);
Log.e(TAG, "onMessageEventPosting:" + Thread.currentThread().getName());
}
// The handler execution thread is the master thread
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEventMain(String str) {
Log.e(TAG, "onMessageEventMain:" + Thread.currentThread().getName());
}
// The handler execution thread is the master thread
@Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
public void onMessageEventMainOrdered(String str) {
Log.e(TAG, "onMessageEventMainOrdered:" + Thread.currentThread().getName());
}
// The handler thread is the background thread
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessageEventBackground(String str) {
Log.e(TAG, "onMessageEventBackground:" + Thread.currentThread().getName());
}
// The handler thread is the background thread
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onMessageEventAsync(String str) {
Log.e(TAG, "onMessageEventAsync:" + Thread.currentThread().getName());
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_skip:// Jump to ModeSendActivity
startActivity(new Intent(this, ModeSendActivity.class));
break; }}@Override
protected void onDestroy(a) {
super.onDestroy();
//2. Anti-registration event
EventBus.getDefault().unregister(this); }}Copy the code
ModeReceiveActivity, as the page that receives the message, is the subscriber, first registered in onCreate() for EventBus, unregistered in onDestroy(), and implements several thread-mode subscriber event handlers. Print the log for the Thread receiving the data with Thread name thread.CurrentThread ().getName(). Click the button to jump to the ModeSendActivity publisher and publish the event in the main Thread.
/** * Several thread modes * send events */
public class ModeSendActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mode_send);
findViewById(R.id.btn_send).setOnClickListener(this);
mTv_content = findViewById(R.id.tv_content);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:// Publish events
mTv_content.setText("Publish events to ModeReceiveActivity");
//4. Publish events
EventBus.getDefault().post("Received the event sent from ModeSendActivity.");
break; }}}Copy the code
Click the Publish event button on ModeSendActivity to send an event to ModeReceiveActivity, where the publish thread is the main thread. The printed data is as follows:
As you can see, the POSTING thread is the same as the POSTING thread. MAIN and MAIN_ORDERED mode threads are the master thread, while BACKGROUND and ASYNC mode threads are BACKGROUND threads.
2. Event priority
EventBus supports specifying the priority of event delivery when defining subscriber event handling methods. By default, the event priority is 0. A larger value indicates a higher priority. In the same thread mode, the event with a higher priority receives the event before the event with a lower priority.
Note: Priority is valid only in the same thread mode.
@Subscribe(threadMode = ThreadMode.MAIN, priority = 0)
public void onMessageEvent(String str) {
//TODO does something after receiving the event
}
Copy the code
- Priority: event priority. The value is an int. The default value is 0. The higher the value, the higher the priority. In the same thread mode, the higher the priority receives the event first than the lower the priority.
Let’s create two activities to verify that PriorityReceiveActivity implements subscriber event handling methods, multiple methods with different priorities, and PrioritySendActivity is responsible for publishing events. PriorityReceiveActivity.java
/** * Event priority * Register and receive events */
public class PriorityReceiveActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "PriorityReceiveActivity";
private TextView mTv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_priority_receive);
findViewById(R.id.btn_skip).setOnClickListener(this);
mTv_content = findViewById(R.id.tv_content);
//1. Register event
EventBus.getDefault().register(this);
}
//3. Subscriber receive event handler, event priorities 0,1,2
@Subscribe(threadMode = ThreadMode.MAIN, priority = 0)
public void onMessageEvent(String str) {
//TODO does something after receiving the event
mTv_content.setText("onMessageEvent:" + str);
Log.e(TAG, "onMessageEvent:priority = 0 " + str);
}
@Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
public void onMessageEvent1(String str) {
Log.e(TAG, "onMessageEvent:priority = 1 "+str);
}
@Subscribe(threadMode = ThreadMode.MAIN, priority = 2)
public void onMessageEvent2(String str) {
Log.e(TAG, "onMessageEvent:priority = 2 " + str);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_skip:// Jump to PrioritySendActivity
startActivity(new Intent(this, PrioritySendActivity.class));
break; }}@Override
protected void onDestroy(a) {
super.onDestroy();
//2. Anti-registration event
EventBus.getDefault().unregister(this); }}Copy the code
Here we define a handler with priority = 0, 1, and 2. Register EventBus in onCreate(), unregister onDestroy(), and click the button to jump to PrioritySendActivity.
/** * Event priority * Send event */
public class PrioritySendActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_priority_send);
findViewById(R.id.btn_send).setOnClickListener(this);
mTv_content = findViewById(R.id.tv_content);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:// Publish events
mTv_content.setText("Publish event to PriorityReceiveActivity");
//4. Publish events
EventBus.getDefault().post("Received the event sent from PrioritySendActivity.");
break; }}}Copy the code
Click the Publish Event button to publish the event to PriorityReceiveActivity and receive the data as follows:
Print the log as follows:
As can be seen from the data, priority = 0<1<2. The one with a higher priority receives data first than the one with a lower priority.
5. Use of AndroidEventBus
When a publisher sends an event, the event is delivered simultaneously to one or more subscribers of the event. If the event object type of the published event matches the subscriber processing event method object type, all registered events that match are received.
// Publish events
EventBus.getDefault().post(new MessageEvent());
// Multiple functions that receive event handling
// Receive Activity1 event processing
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEventActivity1(MessageEvent message) {
//TODO does something after receiving the event
Log.e(TAG, "onMessageEventActivity1 ==");
}
// Receive Activity2 event processing
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEventActivity2(MessageEvent message) {
//TODO does something after receiving the event
Log.e(TAG, "onMessageEventActivity2 ==");
}
Copy the code
OnMessageEventActivity1 () and onMessageEventActivity2() both subscribe to events in the same Activity, but from different publishers, Publish event If the event type in post(Object Event) is the same as the event type in onMessageEvent(Object Event), the published data will be received. The printed data is as follows:
Of course, we can specify different event object types, or add flags to the event object types, such as adding type to MessageEvent. But if they’re both events and they’re all strings then you can’t tell the difference.
1. AndroidEventBus
We can use AndroidEventBus. EventBus is the core class of the AndroidEventBus framework and also the user entry class. It stores the subscriber information and methods registered by the user. The EventType and the tag corresponding to the event identify a kind of event EventType. Each event should have one or more subscribers, and the subscription function in the subscribers passes@Subscriber
Annotations to identify tags and thread models make the checkup user friendly and the code cleaner.
AndroidEventBus differs from EventBus in that it has a tag corresponding to the event and the subscription function in the Subscriber through the @subscriber annotation (EventBus is @subscribe).
// The publisher publishes the event with the tag from_three
EventBus.getDefault().post(new MessageEvent("Received the event sent from AndroidBusSendActivity."), "from_three");
// Subscriber event handler with tag from_three
@Subscriber(tag = "from_three", mode = ThreadMode.MAIN)
public void eventAndroidEventBus(MessageEvent message) {}Copy the code
- Post (Object Event, String Tag) : a method used by publishers to publish events. Event indicates the event to be published. Tag Indicates the event identifier, which is used to distinguish other events. The tag type is a String (case sensitive).
- @subscriber: The @subscriber annotation must be used to define the Subscriber method, otherwise the event handling method will not take effect. Similar to @subscribe in EventBus;
- Tag: Indicates the tag of an event, which is used to distinguish other events. Corresponds to the tag of the published event;
- Mode: Specifies the thread in which the execution is performed. Similar to EventBus threadMode.
2. AndroidEventBus Common event
AndroidEventBus is used in much the same way as EventBus, first adding dependencies to build.gradle:
implementation 'org. Simple: androideventbus: 1.0.5.1'
Copy the code
Then create two Activity, AndroidBusSendActivity publishers publish event, AndroidBusReceiveActivity in onCreate () and onDestroy (), registered in the register event, Implement multiple subscriber event handling methods for different tags.
Note that you need to use the AndroidEventBus package org.simple.eventbus
import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;
/** * AndroidEventBus * receive message page */
public class AndroidBusReceiveActivity extends AppCompatActivity implements View.OnClickListener{
public static final String TAG = "AndroidEventBus";
private TextView mTv_content, mTv_content2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_receive);
findViewById(R.id.btn_skip).setOnClickListener(this);
mTv_content = findViewById(R.id.tv_content);
mTv_content2 = findViewById(R.id.tv_content2);
//1. Register event
EventBus.getDefault().register(this);
}
//3. Receive event handler with from_three tag
@Subscriber(tag = "from_three", mode = ThreadMode.MAIN)
public void eventAndroidEventBus(MessageEvent message) {
mTv_content2.setText("eventAndroidEventBus: tag = from_three | " + message.name);
Log.e(TAG, "eventAndroidEventBus == tag = from_three | " + message.name);
}
// Receive event handler with tag FROM_THREE
@Subscriber(tag = "FROM_THREE", mode = ThreadMode.MAIN)
public void eventAndroidEventBus1(MessageEvent message) {
mTv_content.setText("eventAndroidEventBus: tag = FROM_THREE | " + message.name);
Log.e(TAG, "eventAndroidEventBus1 == tag = FROM_THREE | " + message.name);
}
@Override
protected void onDestroy(a) {
super.onDestroy();
//2. Anti-registration event
EventBus.getDefault().unregister(this); }}Copy the code
import org.simple.eventbus.EventBus;
/** * AndroidEventBus * send message page */
public class AndroidBusSendActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_send);
findViewById(R.id.btn_send).setOnClickListener(this);
mTv_content = findViewById(R.id.tv_content);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:// Publish events
mTv_content.setText("Events in AndroidBusReceiveActivity release");
//4. Publish the event with the tag from_three
EventBus.getDefault().post(new MessageEvent("Received the event sent from AndroidBusSendActivity."), "from_three");
break;
default:
break; }}}Copy the code
The effect is as follows:
The printed data is as follows:
As you can see, even if the event type is the same, the event can only be received if the publish event and the subscribe function handle the same tag.
3. Stickiness events on AndroidEventBus
Sticky events can subscribe to events after sending them and also receive them. Unlike normal events, which are registered before publishing, sticky events can be published before registering.
The use of stickiness events on AndroidEventBus is different from that on EventBus. Stickiness events need to be registered on AndroidEventBus, and subscribers’ event handlers do not need to add sticky flags. Take a look at the steps to use The Stickiness event on AndroidEventBus:
(1)onCreate()
Register stickiness events inregisterSticky()
.onDestroy()
Anti-registration event in.
@Override
protected void onCreate(Bundle savedInstanceState) {
//1. Register sticky events
EventBus.getDefault().registerSticky(this);
}
@Override
protected void onDestroy(a) {
super.onDestroy();
//2. Anti-registration event
EventBus.getDefault().unregister(this);
}
Copy the code
(2) Subscriber’s event handler.
//3. Receive sticky event processing with tag from_android_sticky
@Subscriber(tag = "from_android_sticky", mode = ThreadMode.MAIN)
public void eventAndroidEventBus(String message) {
Log.e(TAG, "eventAndroidEventBus == tag = from_android_sticky | " + message);
//5. Remove sticky events
EventBus.getDefault().removeStickyEvent(String.class, "from_android_sticky");
}
Copy the code
Note: Remove sticky events in time if they are no longer needed via the abstract removeStickyEvent().
(3) Publishers publish sticky eventspostSticky()
.
//4. Publish sticky event with tag from_android_sticky
EventBus.getDefault().postSticky("Receive AndroidStickySendActivity sent event!"."from_android_sticky");
Copy the code
We created two Activity, AndroidStickySendActivity cloth first and then jump AndroidStickyReceiveActivity viscous events, After registration EventBus AndroidStickyReceiveActivity created and viscous event message is received.
/** * AndroidEventBus sticky event * send message page */
public class AndroidStickySendActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_send_sticky);
findViewById(R.id.btn_send).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:// Publish events
//4. Publish sticky events with tag from_three
EventBus.getDefault().postSticky("Receive AndroidStickySendActivity sent event!"."from_android_sticky");
startActivity(new Intent(this, AndroidStickyReceiveActivity.class));
break; }}}Copy the code
AndroidStickySendActivity button click publish in viscous events, send AndroidStickyReceiveActivity events, then jump to AndroidStickyReceiveActivity.
/** * AndroidEventBus sticky event * receive message page */
public class AndroidStickyReceiveActivity extends AppCompatActivity {
public static final String TAG = "StickyReceiveActivity";
private TextView mTv_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_receive_sticky);
mTv_content = findViewById(R.id.tv_content);
//1. Register sticky events
EventBus.getDefault().registerSticky(this);
}
//3. Receive a sticky event with a from_three tag
@Subscriber(tag = "from_android_sticky", mode = ThreadMode.MAIN)
public void eventAndroidEventBus(String message) {
mTv_content.setText("eventAndroidEventBus == tag = from_android_sticky | " + message);
Log.e(TAG, "eventAndroidEventBus == tag = from_android_sticky | " + message);
//5. Remove sticky events
EventBus.getDefault().removeStickyEvent(String.class, "from_android_sticky");
}
@Override
protected void onDestroy(a) {
super.onDestroy();
//2. Anti-registration event
EventBus.getDefault().unregister(this); }}Copy the code
AndroidStickyReceiveActivity complete create and register EventBus, realize the subscriber viscous event handling methods, receives the event data sent by viscosity, results are as follows:
The printed data is as follows:
Note: the parameter type of the sending event must be the same as the parameter type of the receiving event, otherwise the event cannot be received.
- The source address
Pay attention and don’t get lost
Well, everyone, that’s all for this article. Thank you so much for reading this article and seeing the talent here. I am Suming, thank you for your support and recognition, your thumbs up is the biggest motivation for my creation, we will see you in the next article!
If there are any mistakes in this blog, please comment, thank you very much!