An overview of the
EventBus is a publish/subscribe EventBus optimized for Android. The main function is to replace Intent,Handler,BroadCast messages between fragments, activities, services, and threads. It simplifies the communication between components within the application and between components and background threads. The advantages are lower overhead and more elegant code. And decouple the sender from the receiver. For example, when the network is returned, the UI is notified through Handler or Broadcast. Two fragments need to communicate with each other through listeners. EventBus can be used to fulfill these requirements.
As a message bus, EventBus has three main elements:
-
Event: indicates an Event. It can be any type of object
-
Subscriber: Event Subscriber to receive specific events. In EventBus, conventions are used to specify event subscribers to simplify usage. So all event subscriptions are functions that start with onEvent, and specifically, the names of these functions are onEvent, onEventMainThread, onEventBackgroundThread, onEventAsync, This has to do with ThreadMode (below).
-
Publisher: notifies Subscriber of an event. You can send events anywhere in any thread, call the EventBus. post(Object) method directly, and instantiate the eventBus Object yourself, but the default singleton is generally fine: Eventbus.getdefault (), based on the type of the post function argument, will automatically call the function that subscribed to the corresponding type of events.
About ThreadMode
As mentioned above, Subscriber functions can only be those 4, because each event subscription function is associated with a ThreadMode, which specifies the function to be called. There are four threadModes:
-
PostThread: Events are processed in the same process as events are sent, so the event processing time should not be too long, otherwise it affects the event sending thread, which may be the UI thread. The corresponding function name is onEvent.
-
MainThread: Event processing is performed in the UI thread. The event processing time should not be too long, this needless to say, will be ANR, the corresponding function name is onEventMainThread.
-
BackgroundThread: The processing of the event is going to be done in a BackgroundThread, and the corresponding function is called onEventBackgroundThread, and even though it’s called BackgroundThread, the processing of the event is done in the BackgroundThread, the processing of the event shouldn’t take too long, because if the thread that’s sending the event is a BackgroundThread, Events are executed directly, and if the current thread is a UI thread, they are added to a queue, and one thread processes them in turn. If one event takes too long, it blocks the dispatch or processing of subsequent events.
-
Async: Event processing is performed in separate threads and is mainly used to perform time-consuming operations in background threads. Each event starts one thread (thread pool), but it is best to limit the number of threads.
Depending on the event subscription function name, a different ThreadMode is used than if data is loaded in the background thread to be displayed in the UI thread, the subscriber simply names the function onEventMainThread.
To further explain the corresponding function names:
OnEvent: If an onEvent is used as a subscription function, the onEvent will run in the same thread in which the event was published, that is, in the same thread that publishes the event and receives the event. When you use this method, you cannot perform time-consuming operations in the onEvent method, which would delay event distribution.
OnEventMainThread: If you use onEventMainThread as a subscription function, the onEventMainThread will be executed in the UI thread regardless of the thread in which the event is published, and the receiving event will be run in the UI thread. This is useful in Android, where the UI can only be updated in the UI thread, so time-consuming operations cannot be performed in the onEvnetMainThread method.
OnEventBackground: If you use onEventBackgrond as the subscription function, then if the event is 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.
Basic usage
Introducing the EventBus:
The compile 'org. Greenrobot: eventbus: 3.0.0'Copy the code
Define events:
public class MessageEvent { /* Additional fields if needed */ }Copy the code
Register event recipients:
eventBus.register(this);Copy the code
Send event:
eventBus.post(event)Copy the code
Receive messages and process:
public void onEvent(MessageEvent event) {}Copy the code
Logout event reception:
eventBus.unregister(this);Copy the code
Finally, proGuard needs to do some extra processing:
#EventBus
-keepclassmembers class ** {
public void onEvent*(**);
void onEvent*(**);
}Copy the code
Practical example
About communication between activities
Step 1: Define a custom Event to encapsulate information
Examples are as follows:
public class UserEvent { private String userName; public UserEvent() { } public UserEvent(String userName) { this.userName = userName; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; }}Copy the code
Step 2: Register subscribers and define processing methods
public class MainActivity extends Activity { private Button btn, fragment_btn; private TextView service_tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Eventbus.getdefault ().register(this); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); }}); fragment_btn = (Button) findViewById(R.id.fragment_btn); fragment_btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, FragmenTestActivity.class); startActivity(intent); }}); service_tv = (TextView) findViewById(R.id.service_tv); startService(new Intent(this, EventTestService.class)); @subscribe public void onEventMainThread(UserEvent Event) {btn.settext (event.getUsername ()); service_tv.setText(event.getUserName()); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); }}Copy the code
Step 3: Send events
public class SecondActivity extends Activity { private Button btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); btn = (Button) findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final UserEvent ue = new UserEvent(); Ue.setusername (" non-famous programmer "); EventBus.getDefault().post(ue); finish(); }}); }}Copy the code
Fragment, fragment,service, etc communication is basically the same as that between activities. There are only a few posts to explain the code. Interested students can download the demo directly, which has the communication between them.
Note the following when using EventBus:
-
The same onEvent function cannot be registered twice, so it cannot be registered in a class and also in a parent class.
-
The receiving of a message determines which receiving method to execute based on the class name in the parameter. That is, the subscriber’s processing method determines the subscription function based on the type of subscription event.
-
Each event can have multiple subscribers.
-
When an event is posted, events of the event class’s parent class are also posted.
-
All event handlers must be of type public void and have only one parameter representing EventType.
The demo contains communication between activities, communication between fragments, and communication between services and activities.