The Android app can be used to deliver messages with broadcast, Intent, handle, etc., using Eventbus to replace some of their features, and make the code very concise and elegant.
After you import the Eventbus package, you are ready to use it, using the following method
Send Message
Object obj = new Object () Eventbus.getdefault (). Post (obj);
The class that receives the message needs to be registered before it is logged off when the class is destroyed. Generally receive messages are activity classes, so they are registered in the OnCreate function, write-off in the OnDestroy function
@Overrideprotected void OnCreate (Bundle savedinstancestate) { super.oncreate (savedinstancestate); Eventbus.getdefault (). Register (this);} @Overrideprotected void OnDestroy () { Super.ondestroy (); Eventbus.getdefault (). Unregister (this);}
The receive has four functions to choose from, and their differences are as follows
Publish events and accept events on the same thread, avoiding complex time-consuming operations public void OnEvent (Object obj) { System.out.println ("do something"); } The Receive event executes in the UI thread, and you can modify the UI interface public void Oneventmainthread (Object obj) { System.out.println ("do something"); } //If a send event is emitted from a UI event, the receive event executes in the child thread ///If the Send event itself is emitted from a child thread, the receive event and send event are public void in the same thread Oneventbackground (Object obj) { System.out.println ("do something"); } The new child thread receives the public void Oneventasync (Object obj) { System.out.println ("do something"); }
Eventbus is sent according to the parameter identification, such as post (a), then the receiving time will determine whether the parameter is class A, if it is sent to this receive function.
Eventbus is a typical observer pattern, Eventbus is the message sender, and other registered classes belong to the message subscribers. It is internally distributed based on the subscriber's receive type.
Eventbus Source Address: Https://github.com/greenrobot/EventBus
Use of Eventbus