Android Development Note-Explore Eventbus

Source: Internet
Author: User

1, about Eventbus:

Component communication is unavoidable in Android development, and as business requirements complicate, the complexity of the business logic that needs to be addressed in the code is increasing. For example, data transfer between multiple fragment, service and activity, communication between fragment, broadcast and activity, fragment communication, The use of various startactivityforresult, cumbersome operation so that we are tired, on GitHub to find the next solution, found a good open source library Eventbus, I believe many have done Android development friends are more or less to understand this.

The Eventbus is a publish/Subscribe event bus optimized for Android. The main function is to substitute intent,handler,broadcast for passing messages between Fragment,activity,service and threads. The advantage is that the cost is small and the code is more elegant. and decoupling the sender and receiver.

This is Eventbus's Open Source Library on GitHub address: Https://github.com/greenrobot/EventBus

Eventbus's general relationship is this: Subscribers (subscriber) to the bus by subscribing to events (events), event Publishers (publisher) publish events to the bus by subscribers (subscriber) to receive, In fact, it is the observer pattern in software design mode. Eventbus in the use of the time is to publish an event in the appropriate place, so that the registration of the event received by the object can be notified, the corresponding operation.

2, Preliminary discussion Eventbus:

Genteel's text description is boring, go straight to the code and talk, first look at the effect you want to achieve:

  

Seemingly simple effect, click the button jump interface, use intent send a message, and then TextView receive display. This is the traditional practice, if it is true, then the writing of this article is completely meaningless. In fact, this is the use of Eventbus, and did not use the intent to pass the message.

First look at the specific code (remember to add a reference to Eventbus), and then I then branch to parse:

1  PackageCom.lcw.rabbit.eventbusdemo.eventbusdemo;2 3 Importandroid.content.Intent;4 ImportAndroid.os.Bundle;5 Importandroid.support.v7.app.AppCompatActivity;6 ImportAndroid.view.View;7 ImportAndroid.widget.Button;8 ImportAndroid.widget.TextView;9 Ten ImportDe.greenrobot.event.EventBus; One  A  Public classMainactivityextendsappcompatactivity { -  -     PrivateButton mbt_1; the     PrivateTextView mtv_1; -  - @Override -     protected voidonCreate (Bundle savedinstancestate) { +         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main); +         //Registering Bindings Eventbus AEventbus.getdefault (). Register ( This); at  - Initview (); - initaction (); -  -     } -  in     Private voidinitaction () { -Mbt_1.setonclicklistener (NewView.onclicklistener () { to @Override +              Public voidOnClick (View v) { -StartActivity (NewIntent (mainactivity. This, Secondactivity.class)); the             } *         }); $     }Panax Notoginseng  -     Private voidInitview () { theMbt_1 =(Button) Findviewbyid (r.id.bt_1); +Mtv_1 =(TextView) Findviewbyid (R.ID.TV_INFO1); A     } the  +  -     //receive the message you subscribed to $      Public voidOneventmainthread (MyEvent myevent) { $         if(Myevent.getinfo ()! =NULL) { - Mtv_1.settext (Myevent.getinfo ()); -         } the  -     }Wuyi  the  - @Override Wu     protected voidOnDestroy () { -         Super. OnDestroy (); About         //Unbind Eventbus $Eventbus.getdefault (). Unregister ( This); -     } -}
Mainactivity.java
1  PackageCom.lcw.rabbit.eventbusdemo.eventbusdemo;2 3 ImportAndroid.os.Bundle;4 Importandroid.support.v7.app.AppCompatActivity;5 ImportAndroid.view.View;6 ImportAndroid.widget.Button;7 ImportAndroid.widget.Toast;8 9 ImportDe.greenrobot.event.EventBus;Ten  One  Public classSecondactivityextendsappcompatactivity { A  -     PrivateButton mbt_2; -  the @Override -     protected voidonCreate (Bundle savedinstancestate) { -         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_second); + Initview (); - initaction (); +  A     } at  -     Private voidinitaction () { -Mbt_2.setonclicklistener (NewView.onclicklistener () { - @Override -              Public voidOnClick (View v) { -Toast.maketext (secondactivity. This, "message Sent", Toast.length_short). Show (); inEventbus.getdefault (). Post (NewMyEvent ("I am the message sent over")); -  to             } +         }); -     } the  *     Private voidInitview () { $Mbt_2 =(Button) Findviewbyid (r.id.bt_2);Panax Notoginseng     } -  the  +}
Secondactivity.java
1  PackageCom.lcw.rabbit.eventbusdemo.eventbusdemo;2 3 /**4 * Created by Lichenwei5 * date:2015-10-116 * time:18:237  */8  Public classMyEvent {9 Ten     PrivateString info; One  A      PublicMyEvent (String info) { -          This. info =info; -     } the  -      PublicString GetInfo () { -         returninfo; -     } +  -      Public voidsetInfo (String info) { +          This. info =info; A     } at}
MyEvent

The above code is very simple, here is just to do not do too many complex operations, you can according to their own project requirements to add the corresponding code.

3. Parsing code:

1, registration Eventbus:

After adding a reference to Eventbus, we can register bindings and bind Eventbus events for any class, the registration method and the anti-registration method are simple, as can be seen in the above code, respectively, register and unregister, The eventbus.getdefault here is to obtain the meaning of the Eventbus instance (singleton).

1 // Registering Bindings Eventbus 2 Eventbus.getdefault (). Register (this); 3 // Unbind Eventbus 4 Eventbus.getdefault (). Unregister (this);

2. Eventbus Event:

Eventbus is flexible, it does not impose any restrictions on events, does not need to inherit or implement any class or interface, can be any type of entity class, like the above code mentioned in the MyEvent.

3. Eventbus Event Publisher:

With the event, we can publish the event, which can then be received by all subscribers who subscribe to the event. Sending events is simple, there are two ways to post with Poststicky:

1 //  2eventbus.getdefault (). Post (Object event); 3 // Delay Send Event 4 Eventbus.getdefault (). Poststicky (Objet event);

4, Eventbus event subscribers:

Eventbus Event subscribers can be any class that has been registered Eventbus, the number of subscribers is not capped (very important, as mentioned below), there are 4 ways to subscribe here, here is the beginning of the onevent, there are some differences:

  1, OnEvent:

If you use OnEvent as the subscription function, the event is published on which thread, and onevent runs in that thread, which means that the publish event and receive event threads are on the same thread. With this approach, time-consuming operations cannot be performed in the OnEvent method, which can lead to delays in event distribution if the execution of time-consuming operations is easy.
  2, Oneventmainthread:

If you use Oneventmainthread as a subscription function, the Oneventmainthread executes in the UI thread regardless of which thread the event was published in, and the receive event runs in the UI thread, which is very useful in Android. Because the new UI can only be followed in the UI thread in Android, it is not possible to perform time-consuming operations in the Onevnetmainthread method.
  3, Oneventbackground:

If you use Oneventbackgrond as the subscription function, if the event is published in the UI thread, then Oneventbackground will run in the child thread, if the event is originally published in a child thread, Then the Oneventbackground function executes directly in the child thread.
 4, Oneventasync:

Using this function as a subscription function, the new child thread is created to execute Oneventasync regardless of which thread the event is published on.

1   Public void onEvent (Object event) {} 2   Public void Oneventmainthread (Object event) {} 3   Public void Oneventbackgroundthread (Object event) {} 4   Public void Oneventasync (Object event) {}

After introducing all the characters in Eventbus, let's take a minute. Subscription/subscription process:

First of all, to become an event subscribers need to first register the Eventbus binding, and then in this class need to write a method beginning with onevent to receive processing message events, and then we need a custom event can be published by the publisher of the event, let the subscribers of the event receive. The release of the event can be published either through the Post method or by the Poststicky method.

4. Some conveniences brought by Eventbus:

The Eventbus is a publish/Subscribe event bus optimized for Android. The main function is to substitute intent,handler,broadcast for passing messages between Fragment,activity,service and threads. The advantage is that the cost is small and the code is more elegant. and decoupling the sender and receiver. This is what we introduced at the beginning of the article, there is not much to say, say a few in the actual development of the use of the place.

For example:

1, when some of the value of a page changes, you need to go to change the corresponding value of multiple pages at the same time, as long as these classes registered to subscribe to the event, then we can easily send a message through post to communicate.

2, at some point, we do not want to publish the event immediately be consumed, but wait until the time is ripe. For example, after liking a detail page, an event is generated, and the event is not immediately consumed, but the user exits the details page, returns to the product list, receives the event, refreshes the adapter, and so on. Actually, that's what we did with Startactivityforresult and Onactivityresult. Here we can use Poststicky to implement such a mechanism.

In a word, eventbus greatly reduces the complexity of communication between our various components, and it also minimizes the hassle of using Activityforresult. The truth deserves highly recommended.

5. Understanding Eventbus

From the source, we can know that when we register the binding Eventbus in the class, it will scan the current class and record all the methods that have been onevent, stored in a map<key,value>, after the event has been posted through post, Based on the type of arguments in the post, Eventbus will look up the corresponding method in the map, find the corresponding thread, and finally use the Java reflection mechanism to execute our method.

Oneventmainthread indicates that this method executes on the UI main thread.

Oneventpostthread indicates that this method executes in the thread that is currently publishing the event.

Backgroundthread indicates that if an event is published on a non-UI main thread, it is executed directly and published in the same threads. If the event is published on the UI thread, join the background task queue and use the thread pool one after another.

Async joins the background task queue and calls with the thread pool, noting that there is no backgroundthread one by one.

Li Cheng
Source: http://www.cnblogs.com/lichenwei/
The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.
is looking at my blog This children's shoes, I see you imposing, there is a faint of the king's Breath, there will be a future! Next to the word "recommended", you can conveniently point it, action quasi, I do not accept a penny, you also good to come back to me!

Android Development Note-Explore Eventbus

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.