EventBus simple tutorial
Hello everyone! First of all, I am a beginner Android programmer. I am new to EventBus (3.0 usage). Please give me some advice on what I mean. This article is not capable-oriented, so it is Easy for the great gods. If you don't talk nonsense, you can directly go to the topic.What is EventBus?EventBus is a release/subscription event bus optimized for Android. The main function is to replace Intent, Handler, and BroadCast to transmit messages between Fragment, Activity, Service, and threads. The advantage is that the overhead is small and the code is more elegant. 1. the output log of the EventBus preliminary experience program running is as follows: EventBus. getDefault (). register (this); registers all methods on the current interface EventBus. getDefault (). post ("Hello EventBus") is a method that is used to search for the current interface parameter and is annotated by @ Subscribe. When the event post is executed in thread 1, the event method is also executed in thread 1.Declaration: The method for defining an event must be public and cannot use modifiers. Otherwise, an error is reported.2. In the thread model mode, the thread model must be specified in the event handler function of EventBus, that is, the thread where the event handler function runs. EventBus usually has four thread models: PostThread (default), MainThread, BackgroundThread, and Async. PostThread: If the thread model specified by the event handler is PostThread, the event handler will run in the thread where the event is released, that is to say, the publishing event and the receiving event are in the same thread. MainThread: if you use the event processing function to specify the thread model as MainThread, the event processing function will be executed in the UI Thread No matter which thread the event is released. This method can be used to update the UI, but cannot process time-consuming operations. BackgroundThread: If the thread model specified by the event handler is BackgroundThread, if the event is released in the UI thread, the event handler will run in the new thread, if an event is originally released in a child thread, the event handler function is executed directly in the thread where the event is published. UI update is prohibited in this event handler function. Async: If the thread model specified by the event processing function is Async, the event processing function will be executed in the new Child Thread No matter which thread the event is released. Similarly, UI update is prohibited in the event handler. Next, let's take a look at the sample output log as follows: Execute the output log for sending events in a new thread as follows: 3. Receive events first using proiority