Android event bus (AndroidEventBus) framework released, android event distribution mechanism

Source: Internet
Author: User
Tags eventbus

Android event bus (AndroidEventBus) framework released, android event distribution mechanism
AndroidEventBus

If you don't know what the event bus is, it doesn't matter. Let's look at this scenario first:

During development, have you ever encountered A function in Activity-B that calls back Activity-A, but Activity cannot manually create an object to set A Listener or something? Do you want to update the interface in Activity or Fragment in a Service? And so on ......

Once you think about it, you will find that the interaction between activities, Fragment and services in Android is troublesome. Maybe we first think of using broadcast receivers to interact between them. For example, in Activity-B, publish A broadcast and register A broadcast receiver in Activity-A to accept the broadcast. However, it is a little complicated to use a broadcast receiver. If you want to pass an object class as data between components, the object class must implement a serialization interface, which is a little expensive! As follows:

// Register the broadcast receiver class ActivityA extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); registerReceiver (new BroadcastReceiver () {@ Override public void onReceive (Context context, Intent intent) {User person = intent. getParcelableExtra ("user") ;}}, new IntentFilter ("my_action "));}//......} // publish broadcast class ActivityB extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); Intent intent = new Intent ("my_action"); intent. putExtra ("user", new User ("mr. simple "); sendBroadcast (intent );}//......} // implement serialization class User implements Parcelable {String name; public User (String aName) {name = aName;} // Code omitted @ Override public void writeToParcel (Parcel dest, int flags) {dest. writeString (name );}}

Is it troublesome! The event bus framework is designed to simplify these operations and reduce coupling between components.
AndroidEventBus is a lightweight event bus framework of the Android platform. It simplifies interaction between components such as Activity, Fragment, and Service, and greatly reduces coupling between them, this makes our code more concise and less coupled, improving the quality of our code.

Before proceeding, you can consider how to implement communication between two Fragment instances in this scenario?
According to the Android official recommendation, the solution is as follows: Communicating with the Activity. the idea is that the Activity implements an interface and converts the Activity into an interface type after the Activity is associated with Fragment-, call back this interface in Fragment at a certain time, and then call the method in Fragment-B from the Activity. Is this process a bit complicated? If you think so, that is why you continue to look at it.

Basic Structure


AndroidEventBus is similar to the observer mode. The register function registers the objects that need to subscribe to the event bus, and finds the subscription method in the object based on the @ Subcriber annotation, these subscription methods and subscription objects are stored in map. When a user publishes an event somewhere, the event bus finds the corresponding subscriber object based on the parameter type and tag of the event, and finally executes the method in the subscriber object. These subscription methods are executed in the thread model specified by the user. For example, mode = ThreadMode. ASYNC indicates that the subscription method is executed in the Child thread. For more details, see the following description.

Different from greenrobot's EventBus
private void onEventMainThread(User aUser) {    // code }

If you have two receiving functions of the same parameter type that must be executed in the main thread, how can you name them? Even if you have two functions that meet the requirements, I actually add user events, but because EventBus only judges the receiving function based on the event parameter type, therefore, both functions are executed. The policy of AndroidEventBus is to add a tag for each event. The parameter type and tag jointly identify the uniqueness of an event, thus ensuring precise event shipping.
This is the difference between AndroidEventBus and EventBus of greenrobot. However, since I do not know much about EventBus of greenrobot, it is very likely that I have mentioned the above errors. If so, please note.

AndroidEventBus was just for learning at first, but after learning the implementation of EventBus, I found it inconvenient to use. I think since I have these feelings, I should also feel the same, after talking in the Development Group, we found that there was such a situation. Therefore, AndroidEventBus was officially launched in the form of an open source library, hoping to help some people who need it. Of course, the growth of this database requires everyone's support and testing. You are welcome to send a pull request.

Use AndroidEventBus

You can follow the steps below to use AndroidEventBus.

  • 1. register the event recipient
Public class YourActivity extends Activity {@ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main_activity); // registers the EventBus object. getDefault (). register (this) ;}@ Override protected void onDestroy () {// do not forget to log out !!!! EventBus. getDefault (). unregister (this); super. onDestroy ();}}
  • 2. Use the Subscriber annotation to identify the Receiving Method in the event receiving object
Public class YourActivity extends Activity {// code ...... // receiving method, default tag, which is executed in the UI thread @ Subcriber private void updateUser (User user User) {Log. e ("", "### update user name =" + user. name);} // contains my_tag. When you post an event, only events with "my_tag" specified will trigger this function, run the command in the UI thread @ Subcriber (tag = "my_tag") private void updateUserWithTag (User user User) {Log. e ("", "### update user with my_tag, name =" + user. name);} // contains my_tag. When a post event is triggered, only the "my_tag" event is specified to trigger this function. // the thread in which the post function is executed, the thread where the function is executed @ Subcriber (tag = "my_tag", mode = ThreadMode. POST) private void updateUserWithMode (User user User) {Log. e ("", "### update user with my_tag, name =" + user. name);} // contains my_tag. When you post an event, only events with "my_tag" specified will trigger this function, run in an independent thread @ Subcriber (tag = "my_tag", mode = ThreadMode. ASYNC) private void updateUserAsync (User user User) {Log. e ("", "### update user async, name =" + user. name + ", thread name =" + Thread. currentThread (). getName ());}}

The receiving function uses tags to identify the event types that can be received, which is the same as the action specified in BroadcastReceiver, so that messages can be delivered accurately. Mode can specify the thread in which the target function is executed. By default, the target function is executed in the UI thread to facilitate UI updates. When the target method executes the time-consuming operation, you can set the mode to ASYNC to execute the operation in the Child thread.

  • 3. Issue events in other components, such as Activity, Fragment, and Service.
    EventBus.getDefault().post(new User("android"));    // post a event with tag, the tag is like broadcast's action    EventBus.getDefault().post(new User("mr.simple"), "my_tag");

After an event is published, an object registered with this event type will receive the RESPONSE event.

Github Link

Welcome to the star and fork AndroidEventBus frameworks.

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.