EventBus of android open-source framework

Source: Internet
Author: User
Tags eventbus

EventBus of android open-source framework

What is EventBus? What is the purpose?

EventBus is a publish/subscribe event bus. Simply put, the two agreed on how to communicate, one published the message, and the other agreed on immediately received the message you sent.

Usage: I believe everyone has used Handle for thread communication and callback for communication. Is it very troublesome. EventBus can help reduce many things. No matter you publish an event anywhere, the recipient can immediately receive your message, you do not need to consider the problem of android sub-thread operations on UI threads !!!! This framework is easy to use !!!

Project address:

 

 

Link:

The subscriber can subscribe to multiple events. The sender can publish any events, and the publisher can also be a subscriber.

Specific use:

Subscriber related:

Subscriber: EventBus. getDefault (). register (this );

This method is usually registered in the onCreate method.

Unbind a subscriber: EventBus. getDefault (). unregister (this );

This method is usually unbound from the onDestroy method.

The agreed method to receive the event: EventBus has already stipulated the following four methods:

OnEvent:If onEvent is used as the subscription function, the onEvent will run in the thread where the event is published, that is, the publishing event and the receiving event thread are in the same thread. When this method is used, time-consuming operations cannot be performed in the onEvent method. If time-consuming operations are executed, the event distribution delay is easily caused.
OnEventMainThread:If onEventMainThread is used as the subscription function, onEventMainThread runs in the UI thread and receives the event no matter which thread the event is released, this is very useful in Android, because Android can only follow the new UI in the UI thread, so the onEvnetMainThread method cannot perform time-consuming operations.
OnEventBackground:If onEventBackgrond is used as the subscription function, if the event is released in the UI thread, onEventBackground will run in the Child thread. If the event was originally released in the Child thread, the onEventBackground function is executed directly in the Child thread.
OnEventAsync:When this function is used as the subscription function, a new sub-thread will be created to execute onEventAsync no matter which thread the event is released.

Example: public void onEvent (Object object ){
Log. e (hongliang, onEvent );
}

When the subscriber receives the event, it will automatically execute the above four methods and write a method as needed. If multiple methods are written, the subscriber will execute them.

Maybe you will ask, if multiple classes are subscriber, who will receive the event?

EventBus determines which class receives events based on the parameters of these four methods. If the publisher parameter is the same as the parameters of the four methods of a subscriber, the subscriber's method is executed.

 

Publisher:

Publish events: EventBus. getDefault (). post (new your own event );

It can be released anywhere.

Note the parameters of the post method: EventBus will find the four method parameters of the subscriber based on this parameter and execute them in the same way.

For example:

Publisher: EventBus. getDefault (). post (new String (publisher ));

Subscriber: public void onEvent (String str ){
Log. e (hongliang, str );
}

Because the post parameter is String, the onEvent parameter String in the four methods will be executed.

For more information, see:

Reprinted, please indicate the source: bytes]

1. Overview

 

In recent interviews, I was often asked about EventBus. on github, I took down a copy of EventBus. The address is https://github.com/greenrobot/eventbus. it is indeed an incorrect framework, and it is mainly used to analyze and analyze events.

EventBus is a publish/subscribe event bus.

This statement should contain four components: publisher, subscriber, event, and bus.

So what is the relationship between the four?

Obviously: The Subscriber subscribes to an event to the bus and the sender publishes the event.

The relationship should be like this:

The subscriber can subscribe to multiple events. The sender can publish any events, and the publisher can also be a subscriber.

Now that we have a general understanding of the basic relationship, we will use case-driven learning to teach you how to use it;

2. Code is the best teacher

I believe everyone knows about Fragment. Now we need this. Two Fragment components form the main interface. The Fragment on the left is a directory, that is, a list, and the Fragment on the right is the details panel;

A. The directory list is obtained from the network.

B. When you click an entry in the directory, the details panel is dynamically updated;

:

 

According to this requirement, our traditional approach is:

A. Directory Fragment enable the thread in onCreate to access the network to obtain data. After obtaining the data, update the interface through handler.

B. Provide an interface in the Fragment of the directory, and register the interface in the details panel. When a click occurs, call back the interface to change the details panel.

In fact, this method is still good, but what changes will happen to our interaction after EventBus? Wait and see.

First, I will mention:

EventBus. getDefault (). register (this); // subscribe to events

EventBus. getDefault (). post (object); // publish an event

EventBus. getDefault (). unregister (this); // cancel the subscription

 

1. MainActivity and Its Layout

 

[Java]View plaincopy
  1. Package com. angeldedevil. eventbusdemo;
  2.  
  3. Import android. OS. Bundle;
  4. Import android. support. v4.app. FragmentActivity;
  5.  
  6. Public class MainActivity extends FragmentActivity
  7. {
  8. @ Override
  9. Protected void onCreate (Bundle savedInstanceState)
  10. {
  11. Super. onCreate (savedInstanceState );
  12. SetContentView (R. layout. activity_main );
  13. }
  14.  
  15. }
    [Html]View plaincopy
    1. Xmlns: tools = http://schemas.android.com/tools
    2. Android: layout_width = match_parent
    3. Android: layout_height = match_parent
    4. Android: baselineAligned = false
    5. Android: divider =? Android: attr/dividerHorizontal
    6. Android: orientation = horizontal
    7. Android: showDividers = middle>
    8.  
    9. Android: id = @ + id/item_list
    10. Android: name = com. angeldedevil. eventbusdemo. ItemListFragment
    11. Android: layout_width = 0dip
    12. Android: layout_height = match_parent
    13. Android: layout_weight = 1/>
    14.  
    15. Android: id = @ + id/item_detail_container
    16. Android: name = com. angeldedevil. eventbusdemo. ItemDetailFragment
    17. Android: layout_width = 0dip
    18. Android: layout_height = match_parent
    19. Android: layout_weight = 2/>
    20.  

    21. We can see that MainActvity does not have a line of code, and the layout file is composed of two Fragment;

       

      2. ItemListFragment

      First, let's look at an object class:

       

      [Java]View plaincopy
      1. Package com. angeldedevil. eventbusdemo;
      2.  
      3. Import java. util. ArrayList;
      4. Import java. util. List;
      5.  
      6. Public class Item
      7. {
      8. Public String id;
      9. Public String content;
      10.  
      11. Public static List ITEMS = new ArrayList ();
      12. Static
      13. {
      14. // Add 6 sample items.
      15. AddItem (new Item (1, Item 1 ));
      16. AddItem (new Item (2, Item 2 ));
      17. AddItem (new Item (3, Item 3 ));
      18. AddItem (new Item (4, Item 4 ));
      19. AddItem (new Item (5, Item 5 ));
      20. AddItem (new Item (6, Item 6 ));
      21. }
      22.  
      23. Private static void addItem (Item item)
      24. {
      25. ITEMS. add (item );
      26. }
      27.  
      28. Public Item (String id, String content)
      29. {
      30. This. id = id;
      31. This. content = content;
      32. }
      33.  
      34. @ Override
      35. Public String toString ()
      36. {
      37. Return content;
      38. }
      39. }

         

         

        [Java]View plaincopy
        1. Package com. angeldedevil. eventbusdemo;
        2.  
        3. Import android. OS. Bundle;
        4. Import android. support. v4.app. ListFragment;
        5. Import android. view. View;
        6. Import android. widget. ArrayAdapter;
        7. Import android. widget. ListView;
        8.  
        9. Import com. angeldedevil. eventbusdemo. Event. ItemListEvent;
        10.  
        11. Import de. greenrobot. event. EventBus;
        12.  
        13. Public class ItemListFragment extends ListFragment
        14. {
        15.  
        16. @ Override
        17. Public void onCreate (Bundle savedInstanceState)
        18. {
        19. Super. onCreate (savedInstanceState );
        20. // Register
        21. EventBus. getDefault (). register (this );
        22. }
        23.  
        24. @ Override
        25. Public void onDestroy ()
        26. {
        27. Super. onDestroy ();
        28. // Unregister
        29. EventBus. getDefault (). unregister (this );
        30. }
        31.  
        32. @ Override
        33. Public void onViewCreated (View view, Bundle savedInstanceState)
        34. {
        35. Super. onViewCreated (view, savedInstanceState );
        36. // Enable the thread loading list
        37. New Thread ()
        38. {
        39. Public void run ()
        40. {
        41. Try
        42. {
        43. Thread. sleep (2000); // simulate the latency
        44. // Events published in the background thread
        45. EventBus. getDefault (). post (new ItemListEvent (Item. ITEMS ));
        46. } Catch (InterruptedException e)
        47. {
        48. E. printStackTrace ();
        49. }
        50. };
        51. }. Start ();
        52. }
        53.  
        54. Public void onEventMainThread (ItemListEvent event)
        55. {
        56. SetListAdapter (new ArrayAdapter (GetActivity (),
        57. Android. R. layout. simple_list_item_activated_1,
        58. Android. R. id. text1, event. getItems ()));
        59. }
        60.  
        61. @ Override
        62. Public void onListItemClick (ListView listView, View view, int position,
        63. Long id)
        64. {
        65. Super. onListItemClick (listView, view, position, id );
        66. EventBus. getDefault (). post (getListView (). getItemAtPosition (position ));
        67. }
        68.  
        69. }

           

          ItemListFragment subscribes to events in onCreate and cancels events in onDestroy. In onViewCreated, we simulate a subthread to load data over the network. After obtaining the data, we call

          EventBus. getDefault (). post (new ItemListEvent (Item. ITEMS); released an event;

          OnListItemClick is the click event of ListView. We call EventBus. getDefault (). post (getListView (). getItemAtPosition (position); To publish an event,

          GetListView (). getItemAtPosition (position) is of the Item type;

          You must have noticed some strange things. After getting data from new Thread (), handler was not used. Our interface has changed, when will the List be bound?

          Take a closer look at the code and find this method:

          Public void onEventMainThread (ItemListEvent event)
          {
          SetListAdapter (new ArrayAdapter (GetActivity (),
          Android. R. layout. simple_list_item_activated_1,
          Android. R. id. text1, event. getItems ()));
          }

          This method should be used to bind data to the List. So how is this method called?

          Now let's talk about subscription and release events:

          If the method name starts with onEvent, it indicates that you want to subscribe to an event. MainThread means that this method will be executed in the UI thread. When the event is published, this method will be executed.

          When will this event be released?

          The onEventMainThread trigger time should be after the new Thread () execution is complete. We can see that after the sub-Thread execution is complete, EventBus is executed. getDefault (). post (new ItemListEvent (Item. ITEMS ));

          This means that an event is released. When this event is released, our onEventMainThread is executed. What is the association between the two?

          In fact, the onEventMainThread needs to receive an ItemListEvent and we have released an ItemListEvent instance.

          Now let's take a complete look:

          Run EventBus. getDefault (). register (this) in onCreate. this indicates that EventBus can scan the current class and record all methods starting with onEvent. How can this be recorded? Map is used, and Key is the parameter type of the method. Value contains our method.

          In this way, after onCreate is executed, our onEventMainThread has been stored in EventBus as a key-value pair.

          Then, when the sub-thread is executed, call EventBus. getDefault (). post (new ItemListEvent (Item. (ITEMS), EventBus will find the correct method in Map based on the type of the real parameter in post, so it finds our onEventMainThread and finally calls reflection to execute our method.

          Now we should understand the entire running process. If there is no interface, the callback can be explained as well.

          Now let's look at the code. when the Item is clicked, EventBus. getDefault (). post (getListView (). getItemAtPosition (position); we also released an event with the parameter Item. This event aims to allow the Fragment of detailed information to update data, needless to say, according to the above speculation, in the Fragment of detailed information, there is a method like this: public void onEventMainThread (Item item); isn't it? Let's see.

          3. ItemDetailFragment

           

          [Java]View plaincopy
          1. Package com. angeldedevil. eventbusdemo;
          2.  
          3. Import android. OS. Bundle;
          4. Import android. support. v4.app. Fragment;
          5. Import android. view. LayoutInflater;
          6. Import android. view. View;
          7. Import android. view. ViewGroup;
          8. Import android. widget. TextView;
          9. Import de. greenrobot. event. EventBus;
          10.  
          11. Public class ItemDetailFragment extends Fragment
          12. {
          13.  
          14. Private TextView tvDetail;
          15.  
          16. @ Override
          17. Public void onCreate (Bundle savedInstanceState)
          18. {
          19. Super. onCreate (savedInstanceState );
          20. // Register
          21. EventBus. getDefault (). register (this );
          22. }
          23.  
          24. @ Override
          25. Public void onDestroy ()
          26. {
          27. Super. onDestroy ();
          28. // Unregister
          29. EventBus. getDefault (). unregister (this );
          30. }
          31.  
          32. /** Some events will be sent when List is clicked, and details will be updated after the event is received */
          33. Public void onEventMainThread (Item item)
          34. {
          35. If (item! = Null)
          36. TvDetail. setText (item. content );
          37. }
          38.  
          39. @ Override
          40. Public View onCreateView (LayoutInflater inflater, ViewGroup container,
          41. Bundle savedInstanceState)
          42. {
          43. View rootView = inflater. inflate (R. layout. fragment_item_detail,
          44. Container, false );
          45. TvDetail = (TextView) rootView. findViewById (R. id. item_detail );
          46. Return rootView;
          47. }
          48. }
            As expected, the onEventMainThread (Item item) method exists. Of course, you must first write EventBus. getDefault (). register (this) in onCreate; let EventBus scan again.

             

            The Fragment process is: When onCreate is used, EventBus scans the current class and stores onEventMainThread as a key-value pair. The key is Item. class, and the value is the object containing the method.

            When the Item in ItemListFragment is clicked, an event: EventBus. getDefault (). post (getListView (). getItemAtPosition (position); the real parameter type is exactly Item, which triggers our

            OnEventMainThread method, and pass the Item real parameters in. We update the control.

            4. Event

            There is also an event class:

             

            [Java]View plaincopy
            1. Package com. angeldedevil. eventbusdemo;
            2.  
            3. Import java. util. List;
            4.  
            5. Public class Event
            6. {
            7. /** List loading event */
            8. Public static class ItemListEvent
            9. {
            10. Private List Items;
            11.  
            12. Public ItemListEvent (List Items)
            13. {
            14. This. items = items;
            15. }
            16.  
            17. Public List GetItems ()
            18. {
            19. Return items;
            20. }
            21. }
            22.  
            23. } ItemListEvent is used in ItemListFragment as a parameter in onEventMainThread. Why is this class encapsulated? It will be described in later EventBus source code parsing.

               

              The preliminary usage of EventBus has been introduced. Throughout the code, there are handler, AsynTask, and interface callback. but, we implement our needs like magic. Let me know what coupling is, no ~~~

              3. ThreadMode of EventBus

              EventBus contains four threadmodes: PostThread, MainThread, BackgroundThread, and Async.

              We are no stranger to MainThread; we have used it.

              The specific usage is extremely simple. The method name is onEventPostThread, onEventMainThread, onEventBackgroundThread, and onEventAsync.

              What is the difference?

              OnEventMainThread indicates that this method will be executed in the UI thread

              OnEventPostThread indicates that this method will be executed in the thread of the currently released event

              BackgroundThread: if an event is published in a non-UI thread, it is directly executed and published in the same thread. If an event is published in the UI thread, it is added to the background task queue and called one by one using the thread pool.

              Async is added to the backend task queue and called by the thread pool. Note that no BackgroundThread is called one by one.

               

              4. digress

              You can use EventBus to try the following operations:

              When receiving a broadcast, such as a text message, it is displayed on the interface.

              Start a Service, start a scheduled thread in the server, and update the ActivityUI continuously.

              Wait... you will find the charm of EventBus!

               

              I declare that the above two Fragment examples have been put down on the Internet and made some simple changes. Although they are very simple, they can clearly explain the problem. I would like to express my gratitude for writing the package name angeldedevil.

              By the way, let's talk about an official example, what is the performance comparison, and then a bunch of TestCase, which is not intuitive.

               

               

              If you want to have a deep understanding of Eventbus, please refer to: Android EventBus source code parsing will give you a deep understanding of EventBus, and I believe it can help you solve a lot of confusion and understand the beauty of the Framework Design.

               

               

               


               

               

               

               

               

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.