Android Open Source Framework (vii) event bus---Eventbus

Source: Internet
Author: User
Tags eventbus

  

I. INTRODUCTION          Compared with the broadcast broadcast of one of the four components, the broadcast listens mainly to system-level events, such as network switching, battery power, etc., which are inter-process communication, Eventbus is in-process communication.
Learn broadcast you can view this article: Android four components (iii) Broadcastreceiver introduction two. Basic use introduces class libraries:
' com.jakewharton:butterknife:8.5.1 '

When the page opens, Initialize and register Eventbus

// Initialize @Override     protected void onCreate (Bundle savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        //    Register Eventbus  Eventbus.getdefault (). Register (this);}

Release Eventbus registration when page is destroyed

// destroying Eventbus  protectedvoid  OnDestroy () {  Super.ondestroy ();  Eventbus.getdefault (). Unregister (this); }

Publish Event Publish

// Publish Events Eventbus.getdefault (). Post (new Eventbean (" I am from the second page of the trigger "));

Recipient Subscribe. Note The method name can be arbitrarily taken, but the parameter type is consistent with the publish Publisher. This is Eventbean.

// Subscriber events, messages that handle event feedback  publicvoid  OnEvent (Eventbean Bean) {  // get a message from the publisher of event events sent   String msgStr = bean.getmsg ();   // The UI prints out the received message   Tvfirst.settext (MSGSTR);}

Three. Threadmode analysis of five Threadmode introduction
Threadmode.main subscribers will be called in the main thread of Android (sometimes called the UI thread). If the publishing thread is the main thread, the event handler method (the synchronization described in threadmode.posting) is called directly.    Event handlers that use this mode must quickly return to avoid blocking the main thread. Threadmode.main_ordered subscribers will be called in the main thread of Android. The event is always queued for later delivery to subscribers. This gives the event a stricter and more consistent order (hence the name main_ordered). For example, if you use the main threading pattern to publish another event in an event handler, the second event handler completes before the first event handler (because it is called synchronously-compares it to a method call).    With Main_ordered, the first event handler will complete, and the second will be called at a later point in time (as long as the main thread is capable). Threadmode.background subscribers will be called in the background thread. If the publishing thread is not the primary thread, the event handler method is called directly in the publishing thread. If the publishing thread is the main thread, Eventbus will use a background thread to send all events sequentially.    Event handlers that use this mode should return as soon as possible to avoid blocking the background thread. The Threadmode.async event handler method is called in a separate thread. This is always independent of the publishing thread and the main thread. The Publish event never waits for an event handler method that uses this pattern. Event handler methods should use this pattern if their execution may take some time, such as network access. Avoid triggering a large number of long-running asynchronous handler methods at the same time to limit the number of concurrent threads.    Eventbus uses the thread pool to efficiently reuse threads in completed asynchronous event handler notifications. Threadmode.posting this is the default. The subscriber will be called in the same thread that published the event. Event delivery is done synchronously, and all subscribers are called once the release is complete. This threadmode means minimal overhead because it avoids full thread switching. Therefore, for a simple task known to be completed, this is the recommended pattern, which has a short time and does not require the main thread. An event handler that uses this mode should quickly return to avoid blocking the publishing thread, which may be the main thread.
Source view the next five kinds of threadmode different processing methods:
Private voidPosttosubscription (Subscription Subscription, ObjectEvent, Boolean Ismainthread) {        Switch(subscription.subscriberMethod.threadMode) {//send and Subscribers on the same line range             Caseposting:invokesubscriber (subscription,Event);  Break; //Main Thread             CaseMAIN:if(ismainthread) {invokesubscriber (subscription,Event); } Else{mainthreadposter.enqueue (subscription,Event); }                 Break; //              Casemain_ordered:if(Mainthreadposter! =NULL) {mainthreadposter.enqueue (subscription,Event); } Else {                    //temporary:technically not correct as poster no decoupled from subscriberInvokesubscriber (subscription,Event); }                 Break; //background, cannot be processed concurrently             CaseBACKGROUND:if(ismainthread) {backgroundposter.enqueue (subscription,Event); } Else{invokesubscriber (subscription,Event); }                 Break; //Child threads asynchronous concurrency processing             CaseASYNC:asyncPoster.enqueue (subscription,Event);  Break; default:                Throw NewIllegalStateException ("Unknown thread Mode:"+Subscription.subscriberMethod.threadMode); }    }
Four. The sticky event is simply that the event is received after the event is sent and then subscribed to.   Similarly, the same sticky event mechanism, such as sticky Broadcast (Sticky broadcast), is also available in Android. Sticky Event Usage Scenarios:

Some events are published after an event that is interested in information. For example, an event signal, some initialization is complete. Or if you have sensor location data and you want to grab the nearest value. Instead of implementing your own cache, you can use sticky events. Eventbus keeps the specific type of past events in memory. Sticky events can be delivered to the user or explicitly queried. Therefore, you do not need any special logic to consider the available data.

Examples of viscous use:
// 1 Creating a Sticky event class  Public class stickyevent {  public  String msg;    Public stickyevent (String msg) {   this. msg = msg;  }} 
// 2 sending Sticky events Eventbus.getdefault (). Poststicky (new stickyevent (" I am a sticky event "));
 //  3 receive sticky event  @Subscribe (Threadmode = Threadmode.main, sticky = true  )  public  void  stickyeventbus (stickyevent event  ) { //  Tv_eventbus_send_result.settext (event  "    Span style= "COLOR: #000000" >.msg); }
 //  4. Click event handling for the receive Sticky event data button  Bt_eventbus_ Send_sticky.setonclicklistener (new   View.onclicklistener () {@Override  public   void   OnClick (View v) { // true first click to prevent duplicate registration  if   (          Isfirstflag) {Isfirstflag  = false  ;  //  4 register  Eventbus.getdefault () . Register (Eventbussendactivity.       This   
@Override     protected void OnDestroy () {        Super.ondestroy ();         // 5 The solution registration         Eventbus.getdefault (). removeallstickyevents ();        Eventbus.getdefault (). Unregister (eventbussendactivity.  This );    }

Android Open Source Framework (vii) event bus---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.