Eventbus is a subscription/release message bus that implements communication between components and threads within the application. This is convenient to use because the event is of any type.
roles in Eventbus:
Event: Of course it is.
Subscriber: The subscriber of the event, registering first, receiving a specific object, and reclaiming the processing event through ONEVENTXXX ().
Publisher: The publisher of the event, which publishes information via post.
The process is divided into 5 main steps:
1. Defining an Event
2. Register a Subscriber
3. Publish an Event
4. Receive processing an event
5. Logout of a Subscriber
Four ways of handling events oneventxxxx
There are four onevent functions, and the previous example uses only one onevent.
| Name of function |
meaning |
Threadmode |
| OnEvent |
Event handling is performed on the thread that the event is sent |
Postthread |
| Oneventmainthread |
Event is executed on the main thread-ui threads |
Mainthread |
| Oneventbackgroundthread |
Event is executed in a background thread (just a background thread) |
Backgroundthread |
| Oneventasync |
Event will start a single thread execution (each event will start a thread) |
Async |
The first three event handling methods should be completed as soon as possible.
code example under as
In the Build.gradle file under the module, add this sentence under the Dependencies directory
Compile ' de.greenrobot:eventbus:2.4.0 '
In the case of networking, build works, as will automatically download the corresponding jar package on the web. After the build is finished, it can be programmed.
1. Define the event. The code in Firstevent.java is as follows
1 Public classfirstevent {2 3 PrivateString msg;4 Publicfirstevent (String str) {5msg =str;6 }7 8 PublicString getmsg () {9 returnmsg;Ten } One}
2. Register a Subscriber and add the following code to the OnCreate () method in Mainactivity.java
1 eventbus.getdefault (). Register (this);
3. Publish an event. Publish an event in Secondactivity when the button is clicked to post the event, the code is as follows
1 protected voidonCreate (Bundle savedinstancestate) {2 Super. OnCreate (savedinstancestate);3 Setcontentview (r.layout.activity_second);4 5BTN =(Button) Findviewbyid (R.ID.SECOND_BTN);6Btn.setonclicklistener (NewView.onclicklistener () {7 @Override8 Public voidOnClick (View v) {9 Ten //Publish an event OneEventbus.getdefault (). Post (NewFirstevent ("This was an event."))); A } -});
4. Receive and process an event, process the Change event in Mainactivity, and add the following code.
1 Public void Oneventmainthrend (Firstevent event) {2 String str = "This was in main activity," +event.getmsg (); 3 4 LOG.D ("YUQT", str); 5 tv.settext (str); 6 Toast.maketext (this, Str,toast.length_long). Show (); 7 }
5. Unregister the event and sign out in OnDestroy ().
1 protected void OnDestroy () {2 Super . OnDestroy (); 3 Eventbus.getdefault (). Unregister (this); 4 }
Complete.
Using Eventbus in an Android studio environment