EventBus3.0 makes you happy

Source: Internet
Author: User

EventBus3.0 makes you happy

Are you still worrying about refreshing the ui? Are you still wondering how to use the interface callback or handle to implement it? If you want to use the observer mode, an Android open-source framework EventBus is designed to replace Intent, Handler, and BroadCast to transmit messages between Fragment, Activity, Service, and threads. His best advantage is its low overhead, concise code, and code decoupling.

If you have never used eventBus, you are sorry to miss a lot, but it doesn't matter if you officially release eventBus 3.0. There is no big difference in use, but it is better in performance.I personally recommend that you use version 3.0.0 directly, and do not use version 2.4 or 3.0beta1..

Figure-based speech:
EventBus is a publish/subscribe event bus optimized for Android.

As a message bus, EventBus has three main elements:

Event: Event. It can be any type of object Subscriber: Event Subscriber, which receives specific events. In EventBus, conventions are used to specify event subscribers for simplified use. That is, all event subscriptions start with onEvent. Specifically, the function names are onEvent, onEventMainThread, onEventBackgroundThread, and onEventAsync.
ThreadMode (as described below. Publisher: Event Publisher, used to notify Subscriber of an event. You can send events anywhere in any thread and directly call the eventBus. post (Object) method. You can instantiate EventBus by yourself.
Object, but the default Singleton is generally used: EventBus. getDefault (). According to the type of the post function parameter, the function that subscribes to the corresponding type of event is automatically called.
How to Use EventBus:

Introduce eventbus: 2.4.0 (review old version)

Compile 'de. greenrobot: eventbus: 2.4.0'

Introduce eventbus: 3.0.0-beta1

Compile 'de. greenrobot: eventbus: 3.0.0-beta1'

Introduce eventbus: 3.0.0

Compile 'org. greenrobot: eventbus: 3.0.0'

(2) define a message class, which does not inherit any base class or need to implement any interfaces. For example:
public class MessageEvent {    ......}
(3) register an event where you want to subscribe to the event

EventBus. getDefault (). register (this );

(4) Send event: Send message

EventBus. getDefault (). post (messageEvent );

(5) process messages

Before 3.0, EventBus has not used annotation. Message Processing Methods can only be limited to onEvent, onEventMainThread, onEventBackgroundThread, and onEventAsync, representing four thread models respectively. After 3.0, the message processing method can be named at will, but an annotation @ Subscribe needs to be added and the thread model must be specified (beta1 is PostThread by default, and the official version is POSTING by default ), four thread models are described below.
Note: The access permission of the event processing function must be public. Otherwise, an exception is reported.

Differences between EventBus3.0 and EventBus2.4
Public void onEvent (MessageEvent event) {// the thread in which the event is published, onEvent will run in this thread, that is, the publish event and the receive 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. }
Public void onEventMainThread (MessageEvent event) {// no matter which thread the event is released, onEventMainThread will execute in the UI thread and receive the event will run in the UI thread, 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. }
Public void onEventBackgroundThread (MessageEvent event) {// if the event is released in the UI thread, onEventBackground runs in the Child thread, if the event is originally released in a child thread, the onEventBackground function is executed directly in the Child thread. }
Public void onEventAsync (MessageEvent event) {// use this function as the subscription function. No matter which thread the event is published, a new subthread will be created to execute onEventAsync .}
This is the case with EventBus 3.0.0.
(1) beta1
@ Subscribe (threadMode = ThreadMode. PostThread) // 3.0.0-beta1 public void onMessageEventPost (UserEvent event) {// default mode, executed in the sending thread}
@ Subscribe (threadMode = ThreadMode. MainThread) public void onMessageEventMain (UserEvent event) {// executed in the ui thread}
@ Subscribe (threadMode = ThreadMode. BackgroundThread) public void onMessageEventBackground (UserEvent event) {// executed in the background thread}
@ Subscribe (threadMode = ThreadMode. Async) public void onMessageEventAsync (UserEvent event) {// force execution in the background}

(2) official version

@ Subscribe (threadMode = ThreadMode. POSTING) // 3.0.0 public void onMessageEventPost (UserEvent event) {// default mode, executed in the sending thread}
@ Subscribe (threadMode = ThreadMode. MAIN) public void onMessageEventMain (UserEvent event) {// executed in the ui thread}
@ Subscribe (threadMode = ThreadMode. BACKGROUND) public void onMessageEventBackground (UserEvent event) {// executed in the BACKGROUND thread}
@ Subscribe (threadMode = ThreadMode. ASYNC) public void onMessageEventAsync (UserEvent event) {// force execution in the background}
(6) Cancel message subscription

EventBus. getDefault (). unregister (this );

(7) code obfuscation
#EventBus -keepclassmembers class ** {    public void onEvent*(**);    void onEvent*(**); }

Let's take a look at the simple implementation:

Take a look at the specific code usage:

Package com. losileeya. eventbusapp; import android. content. intent; import android. OS. bundle; import android. support. v7.app. appCompatActivity; import android. util. log; import android. view. view; import android. widget. button; import android. widget. textView; import android. widget. toast; import com. losileeya. eventbusapp. event. eventBusEvents; import org. greenrobot. eventbus. eventBus; import org. greenrobot. eventbus. subscribe; import org. greenrobot. eventbus. threadMode; public class MainActivity extends AppCompatActivity implements View. onClickListener {private Button btn_first, btn_second, listener; private TextView TV _toast; private TextView TV _default, TV _main, TV _background, TV _asy; @ Override protected void onCreate (Bundle listener) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); EventBus. getDefault (). register (this); btn_first = (Button) findViewById (R. id. btn_first); btn_second = (Button) findViewById (R. id. btn_second); btn_third = (Button) findViewById (R. id. btn_third); TV _toast = (TextView) findViewById (R. id. TV _toast); TV _default = (TextView) findViewById (R. id. TV _default); TV _main = (TextView) findViewById (R. id. TV _main); TV _background = (TextView) findViewById (R. id. TV _background); TV _asy = (TextView) findViewById (R. id. TV _asy); listener (this); btn_second.setOnClickListener (this); btn_third.setOnClickListener (this) ;}@ Override public void onClick (View v) {Intent intent; switch (v. getId () {case R. id. btn_first: intent = new Intent (MainActivity. this, FirstActivity. class); startActivity (intent); break; case R. id. btn_second: intent = new Intent (MainActivity. this, SecondActivity. class); startActivity (intent); break; case R. id. btn_third: intent = new Intent (MainActivity. this, ThirdActivity. class); startActivity (intent); break ;}@ Subscribe (threadMode = ThreadMode. MAIN) public void onMessageMain (EventBusEvents. firstEvent firstEvent) {TV _toast.setText (firstEvent. getValue (); Toast. makeText (this, firstEvent. getValue (), Toast. LENGTH_SHORT ). show (); Log. d ("zy", "onEventMainThread -->" + Thread. currentThread (). getId (); TV _main.setText (Thread. currentThread (). getId () + "");}/*** use onEvent to receive events, then, execute * @ param event */@ Subscribe (threadMode = ThreadMode. POSTING) public void onPost (EventBusEvents. firstEvent firstEvent) {Log. d ("zy", "onEventPost -->" + Thread. currentThread (). getId (); TV _default.setText (Thread. currentThread (). getId () + "");}/*** use onEventBackgroundThread to receive events. If the Distributed Event runs in the subthread, the received event runs directly in the same thread, if the dispatching event is in the UI thread, a subthread is started to run and receive the event * @ param event */@ Subscribe (threadMode = ThreadMode. BACKGROUND) public void onBackgroundThread (EventBusEvents. firstEvent firstEvent) {Log. d ("zy", "onEventBackgroundThread -->" + Thread. currentThread (). getId (); TV _background.setText (Thread. currentThread (). getId () + "");}/*** use onEventAsync to receive events, regardless of the thread in which the event is distributed (UI or sub-thread, the recipient will execute * @ param event */@ Subscribe (threadMode = ThreadMode. ASYNC) public void onAsync (EventBusEvents. firstEvent firstEvent) {Log. d ("zy", "onEventAsync -->" + Thread. currentThread (). getId (); TV _asy.setText (Thread. currentThread (). getId () + "") ;}@ Override protected void onDestroy () {super. onDestroy (); EventBus. getDefault (). unregister (this );}}
Package com. losileeya. eventbusapp; import android. OS. bundle; import android. support. v7.app. appCompatActivity; import android. view. view; import android. widget. button; import com. losileeya. eventbusapp. event. eventBusEvents; import org. greenrobot. eventbus. eventBus; public class FirstActivity extends AppCompatActivity {private Button btn_showDownLoad; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_first); btn_showDownLoad = (Button) findViewById (R. id. btn_toast); btn_showDownLoad.setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {new Thread (new Runnable () {@ Override public void run () {try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} EventBus. getDefault (). post (new EventBusEvents. firstEvent ("I downloaded text from the Internet "));}}). start ();}});}}

We can see where messages need to be sent, so they must be used:

EventBus. getDefault (). post (your event)

Then you just need to subscribe:

   @Subscribe(threadMode = ThreadMode.MAIN)    public void onMessageMain(EventBusEvents.FirstEvent firstEvent){        tv_toast.setText(firstEvent.getValue());        Toast.makeText(this, firstEvent.getValue(),Toast.LENGTH_SHORT).show();    }

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.