Basic use of message bus EventBus (20)

Source: Internet
Author: User
Tags eventbus

Basic use of message bus EventBus (20)

 

 

(1). Preface:

Today, our project continues to be updated. Today, we will mainly explain the basic usage of the message bus EventBus. In the next article, we will analyze the implementation process from the source code perspective.

FastDev4Android framework project address: https://github.com/jiangqqlmj/FastDev4Android

(2). Introduction:

In the past, we used to distribute and update messages between components. Generally, we used the observer mode or the interface data callback method. However, this method can solve our problem, but the coupling between components is serious, and the code is not easy to read and maintain. To solve this problem, we can use the message bus EventBus framework.

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. And decouple the sender and receiver. EventBus open source website address: https://github.com/greenrobot/eventbus.

The entire subscription and accept architecture is as follows:

EventBus has the following features:

  • Simplify message communication between components
  • Make the code more concise
  • Fast
  • Jar package is very small, less than 50 KB
  • There are also some issues such as communication between threads and priority.

    (3) Usage

    3.1.AndroidStudio implements Gradle configuration as follows:

     

    compile 'de.greenrobot:eventbus:2.4.0'

     

    3. 2. event object definition

     

       publicclass MessageEvent { /* Additional fields if needed */ }

     

    3. register on the receiving page

     

     eventBus.register(this);

     

    3. 4. Message receiving method implementation

     

      public voidonEvent(AnyEventType event) {/* Do something */};

     

    3. 5. Send messages

     

      eventBus.post(event);

     

    OK is the official instructions above. Now we will use an instance to demonstrate the basic use of EventBus.

    (4). Examples

    4. 1. implementation requirement: There is a button and a TextView In the first Activity, then click the button to open the second Activity, there is a button in the second Activity, and click the button to close the second Activity, at the same time, the message is called back to the first Activity and displayed in TextView.

    . We need two Activity la S.

     

     
       
             
         
       

     

     

       
       
             
         
       

     

    4. 3. Create an event management class: TestEventFirst. java

     

    Packagecom. chinaztt. fda. event;/*** current class annotation: EventBus test First class * Project name: FastDev4Android * package name: com. chinaztt. fda. event * Author: Jiang qingqing on 15/11/3 * email: [email protected] * QQ: 781931404 * company: Jiangsu Zhongtian Technology Software Technology Co., Ltd. */public classTestEventFirst {private String msg; public String getMsg () {return msg;} public void setMsg (String msg) {this. msg = msg;} public TestEventFirst (String msg) {this. msg = msg ;}}

     

    4.4: registration and cancellation

    Use EventBus. getDefault (). register (this); for registration

    Use EventBus. getDefault (). unregister (this); to cancel registration

    4. 5. Send messages

    Use EventBus. getDefault (). post (new TestEventFirst (I am the message returned by the second Activity...); send the message

    . Message receipt

    Rewrite the onEventMainThread () method in the registered Activity to process the received message (in addition to this method, there are three other methods, which will be described in the next article)

     

    /*** Handle received messages * @ param event */public voidonEventMainThread (TestEventFirst event) {textView_one.setText (event. getMsg (); showToastMsgShort (event. getMsg ());}

     

    The TestEventFirst parameter in the method is the message class sent, and all the sent messages are encapsulated in it. We only need to use the event object for retrieval and processing.

    . Complete the code for the first Activity and the second Activity as follows:

     

    Packagecom. chinaztt. fda. test; importandroid. OS. bundle; importandroid. view. view; importandroid. widget. button; importandroid. widget. textView; importandroid. widget. toast; importcom. chinaztt. fda. event. testEventFirst; importcom. chinaztt. fda. ui. r; importcom. chinaztt. fda. ui. base. baseActivity; importcom. chinaztt. fda. utils. log; importorg. androidannotations. annotations. click; importorg. androidannotations. annotations. EActivity; importorg. androidannotations. annotations. viewById; importorg. w3c. dom. text; importde. greenrobot. event. eventBus;/*** current class annotation: Data Communication instance between EventBus components * Project name: FastDev4Android * package name: com. chinaztt. fda. author: Jiang qingqing on 15/11/3 * email: [email protected] * QQ: 781931404 * company: jiangsu Zhongtian Technology Software Technology Co., Ltd. */@ EActivitypublic classEventBusTestActivity extendsBaseActivity {Button button_one; TextView textView_one; @ Override protected void onCreate (BundlesavedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. event_bus_test_layout); EventBus. getDefault (). register (this); button_one = (Button) this. findViewById (R. id. button_one); textView_one = (TextView) this. findViewById (R. id. textView_one); button_one.setOnClickListener (newView. onClickListener () {@ Override public void onClick (View v) {openActivity (EventBusTestTwoActivity _. class) ;}}) ;}/ *** handle received messages * @ param event */public voidonEventMainThread (TestEventFirst event) {textView_one.setText (event. getMsg (); showToastMsgShort (event. getMsg () ;}@ Override protected void onDestroy () {super. onDestroy (); EventBus. getDefault (). unregister (this );}}

     

     

    Packagecom. chinaztt. fda. test; importandroid. OS. bundle; importandroid. view. view; importandroid. widget. button; importcom. chinaztt. fda. event. testEventFirst; importcom. chinaztt. fda. ui. r; importcom. chinaztt. fda. ui. base. baseActivity; importorg. androidannotations. annotations. click; importorg. androidannotations. annotations. EActivity; importorg. androidannotations. annotations. viewById; importde. greenrobot. event. eventBus;/*** current class Note: * Project name: FastDev4Android * package name: com. chinaztt. fda. author: Jiang qingqing on 15/11/3 * email: [email protected] * QQ: 781931404 * company: jiangsu Zhongtian Technology Software Technology Co., Ltd. */@ EActivitypublic classEventBusTestTwoActivity extends BaseActivity {Button button_two; @ Override protected void onCreate (BundlesavedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. event_bus_test_two_layout); button_two = (Button) this. findViewById (R. id. button_two); button_two.setOnClickListener (newView. onClickListener () {@ Override public void onClick (View v) {EventBus. getDefault (). post (new TestEventFirst (I am the information returned by the second Activity ....)); eventBusTestTwoActivity. this. finish ();}});}}

     

    At this point, the basic use of EventBus has been completed. Let's take a look at the above demonstration, for more information, see the next 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.