Android Event Bus (i) EventBus3.0 usage full parse

Source: Internet
Author: User

Preface

The Eventbus is a publish/Subscribe event bus optimized for Android. Simplifies communication between components within an application and between components and background threads. The advantage is that the overhead is small, the code is more elegant, and the sender and receiver are decoupled. If activity and activity interact well, it would be a headache if fragment and fragment were interacting, but it would be a bit cumbersome and inefficient to use broadcast, but if the data being passed was an entity class that needed serialization, Then obviously the cost will be a bit high. Today we will learn how to use the EventBus3.0.

1.EventBus Overviewthree elements of Eventbus

Eventbus has three main elements that we need to understand first:

    • Event: Events, which can be any type of object.
    • Subscriber: Event Subscribers, the method of message handling before EventBus3.0 can only be limited to onevent, Oneventmainthread, Oneventbackgroundthread, and Oneventasync, They represent four threading models, respectively. After EventBus3.0, the method of event handling can be arbitrarily named, but need to add an annotation @subscribe, and to specify the threading model (default is posting), four kinds of threading model is described below.
    • Publisher: An event publisher that can send an event anywhere on any thread, calling Eventbus's post (Object) method directly. You can instantiate the Eventbus object yourself, but it is good to use Eventbus.getdefault (), which automatically calls the function that subscribes to the corresponding type of event, depending on the type of the post function parameter.
Eventbus Four types of Threadmode (threading model)

EVENTBUS3.0 has the following four kinds of Threadmode:

    • POSTING (default): If you use an event handler to specify that the threading model is POSTING, the event handler will run in that thread, that is, publish the event and receive the event on the same thread. The thread model avoids time-consuming operations in the event handler for posting, because it blocks the delivery of events and may even cause ANR.
    • MAIN:
      The handling of the event is performed in the UI thread. Event processing time can not be too long, long will be ANR.
    • BACKGROUND: If the event is published in the UI thread, the event handler is run in the new thread, and if the event is originally published in a child thread, the event handler function is executed directly in the thread that publishes the event. UI update operations are prohibited in this event handler.
    • ASYNC: Regardless of which thread the event is published on, the event handler is executed in the newly created child thread, and the UI update operation is prohibited in this event handler function.
2.EventBus Basic Usage

Eventbus is easy to use and is divided into five steps:

1. Customizing an event class

public class MessageEvent {    ...}

2. Register events where you need to subscribe to events

EventBus.getDefault().register(this);

3. Sending events

EventBus.getDefault().post(messageEvent);

4. Handling Events

@Subscribe(threadMode = ThreadMode.MAIN)public void XXX(MessageEvent messageEvent) {    ...}

As we said earlier, the method of message processing can be arbitrarily named, but you need to add an annotation @subscribe, and you want to specify the threading model (default is posting).

5. Canceling an event subscription

EventBus.getDefault().unregister(this);
3.eventbus3.0 Applications

Above the basic usage, some students may be a bit dizzy, here is an example to apply EventBus3.0.

Adding dependent libraries

Android Studio Configuration Gradle:

‘org.greenrobot:eventbus:3.0.0‘
defining Message Event classes
publicclass MessageEvent {    private String message;    publicMessageEvent(String message) {        this.message = message;    }    publicgetMessage() {        return message;    }    publicvoidsetMessage(String message) {        this.message = message;    }}
registering and canceling subscription events

Registration and Unsubscribe events (Mainactivity.java) in mainactivity:

ImportAndroid.content.Intent;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView;ImportOrg.greenrobot.eventbus.EventBus;ImportOrg.greenrobot.eventbus.Subscribe;ImportOrg.greenrobot.eventbus.ThreadMode; Public  class mainactivity extends appcompatactivity {    PrivateTextView Tv_message;PrivateButton Bt_message;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Tv_message= (TextView) This. Findviewbyid (R.id.tv_message); Tv_message.settext ("Mainactivity"); Bt_message= (Button) This. Findviewbyid (R.id.bt_message); Bt_message.settext ("Jump to Secondactivity"); Bt_message.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {StartActivity (NewIntent (mainactivity. This, Secondactivity.class)); }        });//Register eventEventbus.getdefault (). Register ( This); }@Override    protected void OnDestroy() {Super. OnDestroy ();//Unregister eventEventbus.getdefault (). Unregister ( This); } }
event subscribers handle Events

Here our Threadmode is set to main, the handling of the event is executed in the UI thread, and the TextView is used to show the received event message:

   @Subscribe(threadMode = ThreadMode.MAIN)    publicvoidonMoonEvent(MessageEvent messageEvent){        tv_message.setText(messageEvent.getMessage());    }
Event Publishers Publish events

Here secondactivity is created to publish the message:

 Public  class secondactivity extends appcompatactivity {    PrivateButton Bt_message;PrivateTextView Tv_message;@Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);        Setcontentview (R.layout.activity_main); Tv_message= (TextView) This. Findviewbyid (R.id.tv_message); Tv_message.settext ("Secondactivity"); Bt_message= (Button) This. Findviewbyid (R.id.bt_message); Bt_message.settext ("Send Event"); Bt_message.setonclicklistener (NewView.onclicklistener () {@Override             Public void OnClick(View v) {Eventbus.getdefault (). Post (NewMessageevent ("Welcome to Liu Wangshu's blog"));            Finish ();    }        }); }}

OK run the program, we see mainactivity textview display mainactivity words:

Next we click the button to enter secondactivity and click the Send Event button in the interface, then Secondactivity is finish off, mainactivity TextView show "Welcome to Liu Wangshu Blog":
————————->

4.eventbus3.0 Sticky Events

In addition to the ordinary events described above, Eventbus also supports the sending of sticky events, that is, subscribing to the event after the event is sent and receiving the event, similar to sticky broadcasts. In order to verify the sticky event We modify the previous code:

Subscribe to Sticky events

In mainactivity we add the Register event to the button's Click event:

  bt_subscription.setOnClickListener(new View.OnClickListener() {            @Override            publicvoidonClick(View v) {                //注册事件                EventBus.getDefault().register(MainActivity.this);            }        });
Sticky events handled by subscribers

Write a new method in mainactivity to handle sticky events:

   @Subscribetrue)    publicvoidononMoonStickyEvent(MessageEvent messageEvent){        tv_message.setText(messageEvent.getMessage());    }
Send Sticky Events

In secondactivity we define a button to send sticky events:

   bt_subscription.setOnClickListener(new View.OnClickListener() {            @Override            publicvoidonClick(View v) {                EventBus.getDefault().postSticky(new MessageEvent("粘性事件"));                finish();            }        });

OK run the code to see the effect, first we do not subscribe to the event in Mainactivity, but instead jump directly to the secondactivity click the Send Sticky event button, then the interface back to Mainactivity, We see that TextView still shows the mainactivity field because we have not subscribed to the event yet.

———————— –>

Next we click Subscribe event, TextView changes show "sticky event", done.

EventBus3.0 use of the temporary analysis to this, do not understand the students can download the source to study, the next talk will explain the source of EventBus3.0.

GitHub Source Download

Resources
Eventbus use of the detailed
Eventbus 3.0 of the use of the explanation
Eventbus of Fast Android development Series communication articles

Android Event Bus (i) EventBus3.0 usage full parse

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.