Android development and learning-use EventBus, android-eventbus

Source: Internet
Author: User
Tags eventbus

Android development and learning-use EventBus, android-eventbus

EventBus is a tool that transfers messages between components by publishing and subscribing to events.

It aims to optimize the process of passing messages between components. Traditional methods for transmitting messages between components include broadcast and callback, which are complicated to use.

Working principle:

Dependency:

1 dependencies {2     compile 'org.greenrobot:eventbus:3.0.0'3 }

Note: EventBus is an event-subscription model. In fact, events are messages, and subscriptions are messages. This article does not strictly differentiate between events and messages, so it is easy to understand!

1. Start with simple: act as Handler

Since a message can be sent, it is the responsibility of Handler to send and receive messages under the same component.

First define an event object:

 1 public class MessageEvent { 2     private String message; 3  4     public MessageEvent(String message) { 5         this.message = message; 6     } 7  8     public String getMessage() { 9         return message;10     }11 12     @Override13     public String toString() {14         return message;15     }16 }

This event Object only needs to be a subclass of the Object. There are no other requirements. The message content can be determined at will. Here, a String is used to represent the event message, and toString is used to directly output the event content.

Bind EventBus to the component that needs to receive messages. Here, the Activity acts as the Subscriber, that is, the message receiver.

1 public class MainActivity extends AppCompatActivity {2 3 @ Override 4 protected void onCreate (Bundle savedInstanceState) {5 super. onCreate (savedInstanceState); 6 setContentView (R. layout. activity_main); 7} 8 9 @ Override10 protected void onStart () {11 super. onStart (); 12 EventBus. getDefault (). register (this); // bind the current Activity to subscriber 13} 14 15 @ Override16 protected void onStop () {17 EventBus. getDefault (). unregister (this); // unbind 18 super. onStop (); 19} 20 21 // declare a subscription Method for Receiving Event 22 @ Subscribe23 public void onEvent (MessageEvent messageEvent) {24 Log. d (TAG, "onEvent () called with: messageEvent = [" + messageEvent + "]"); 25} 26 27}

You can use the EventBus. getDefault method to obtain an EventBus Singleton, that is, each time you call this method, the same EventBus object is obtained. Different EventBus object messages are not interconnected.

Then, bind the EventBus object in the onStart method of the Activity and unbind it from the onStop method. At the same time, you need to define a method for receiving events, and add the @ Subscribe annotation to indicate that this method is used to receive subscription events.

Next, we need to send the event:

1 EventBus.getDefault().post(new MessageEvent("I m Fndroid"));

The default EventBus object obtained here is sent through the post method. The log is as follows:

 

2. Inter-component communication: Replacement of broadcast and callback

EventBus does not exist to replace Handler, but to communicate between components. With the above knowledge, the next step is not difficult.

As we all know, as long as it is a component bound to the same EventBus object (Subscriber), messages are interconnected, that is, we can send events to the Activity in the Service for communication. (Other components are similar)

Define an IntentService and send an event, while Activity is the same as above.

 1 public class MyIntentService extends IntentService { 2  3     public MyIntentService() { 4         super("MyIntentService"); 5     } 6  7     @Override 8     protected void onHandleIntent(Intent intent) { 9         EventBus.getDefault().post(new MessageEvent("From service"));10     }11 12 }

Enable the service in Activity:

1 startService(new Intent(this, MyIntentService.class));

Log:

Communication between components becomes so simple.

 

3. Advanced: persistent event, thread mode, priority

① StickyEvent): For a common message sent by calling the post method, the message will be consumed when it is received for the first time, that is, the message will disappear after processing in the @ Subscribe method. EventBus provides another type of message, StickyEvent, which will be stored in RAM until the next StickyEvent is sent. Each EventBus object can use the geStickyEvent method to obtain the most recent persistent event.

We make a slight modification to the Activity and print the current persistent message in the subscription method:

1 // declare a subscription method to receive events 2 @ Subscribe3 public void onEvent (MessageEvent messageEvent) {4 Log. d (TAG, "onEvent () called with: messageEvent = [" + messageEvent + "]"); 5 Log. d (TAG, "onEvent: Sticky Event = [" + EventBus. getDefault (). getStickyEvent (MessageEvent. class) + "]"); 6}

Then modify the Service to send a StickyEvent:

1     @Override2     protected void onHandleIntent(Intent intent) {3         EventBus.getDefault().post(new MessageEvent("From service"));4         EventBus.getDefault().postSticky(new MessageEvent("From service2"));5         EventBus.getDefault().post(new MessageEvent("From service3"));6     }

We can see that the postSticky method is called to send an event during the second sending, which indicates that the event is a persistent event, unless a new persistence event of the same type (different types of events can coexist) is sent, it will be stored in the memory and can be obtained at any time.

Log:

We can see that when the message is received for the third time, StickyEvent is printed and still "From service2 ".

Similarly, if we want to remove this persistent event, we can call the removeStickyEvent method of EventBus. If we want to remove all types of persistent events, we can call the removeAllStickyEvent method.

② Thread mode

EventBus allows us to set threads for subscribers,By default, subscription is in the same thread as event sending.To print out the subscribed thread id.

Modify the @ Subscribe method in the Activity:

1     @Subscribe2     public void onEvent(MessageEvent messageEvent) {3         Log.d(TAG, "onEvent: Thread id = [" + Thread.currentThread().getId() + "]");4         Log.d(TAG, "onEvent() called with: messageEvent = [" + messageEvent + "]");5     }

Modify the Service to send a common event and output the current thread id:

1     @Override2     protected void onHandleIntent(Intent intent) {3         Log.d(TAG, "onHandleIntent: Thread id = [" + Thread.currentThread().getId() + "]");4         EventBus.getDefault().post(new MessageEvent("From service"));5     }

Print Log:

There are four thread modes for subscribers:

It is easy to set the subscriber thread. You only need to assign values in the annotation, for example:

1     @Subscribe(threadMode = ThreadMode.MAIN)

③ Priority

Each component can have multiple subscription methods, and we can set different priorities for them. The setting method is also simple:

1     @Subscribe(priority = 88)

The default priority is 0. A subscription method with a higher priority will receive the event first, and each subscription method can terminate the event. You can stop the event transfer using the following methods:

1    EventBus.getDefault().cancelEventDelivery(messageEvent);

④ Custom EventBus object

The getDefault method is used to obtain an EventBus default singleton. However, we can use EventBus. Builder to construct a custom EventBus object.

 

After understanding the usage, we can analyze the source code more easily.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.