The interaction between activity, Service, and fragment in Android is cumbersome, with the following methods:
(1) using the broadcast, the sender sends the broadcast, the receiver receives the broadcast to carry on the processing;
(2) Use handler and message, such as download thread to complete the download task, send the UI to Message,ui after receiving a message to update the interface.
But these methods are cumbersome, a relatively simple and effective way is to use the event bus. The basic principle of event bus is that the sender sends the message to the event bus, and then the event bus finds which methods in the receiver register the event and, if a method registers the event, triggers the method. This enables the communication between components to be much simpler than other methods, and the code is more concise.
1. Download the Simple_eventbus.jar and import the Android project, and in the component that needs to send or receive the message, import the following two classes:
Import Org.simple.eventbus.EventBus; import Org.simple.eventbus.Subcriber;
2. Create a new two activity:mainactivity and Activity2. Where mainactivity as the recipient of the message, Activity2 as the sender of the message. Since all two activity uses the event bus, you need to register the Eventbus in OnCreate (Bundle savedinstancestate):
Eventbus.getdefault (). Register (this);
You need to unregister Eventbus in OnDestroy ():
Eventbus.getdefault (). Unregister (this);
3. Create a new Button,onclick () method in Activity2 as follows:
@Override Public voidOnClick (View v) {Switch(V.getid ()) { CaseR.id.btnrun2:num++; Txtstatus.settext ("Clicked" + num + "Times!"); Eventbus.getdefault (). Post (NewObject (), "My_tag"); Break; default: Break; } }
Each time a button is clicked, the Eventbus.getdefault (). Post () method is used to send a message to Eventbus. Eventbus.getdefault (). Post () has two parameters: the first parameter is the object passed to the event receiver, because we do not need to pass the object to the sender, so we only have a new object, and the second parameter is tag, which is equivalent to the action in the broadcast. , only the receiver registered the method of the tag will be triggered, the method is not registered this tag will not be triggered.
4. Create a new method for receiving messages in mainactivity:
@Subcriber (tag = "My_tag") privatevoid UpdateUI (Object o) { num+ +; Txtstatus.settext ("Activity 2 clicked" + num + "Time!") ); LOG.E ("num=", string.valueof (num)); }
where @subcriber (tag = "My_tag") Note that the method is a message receiving method, Tag = "My_tag" indicates that the method registered "My_tag" the message, the method will be triggered to receive the message.
5. Run the results. Enter activity 2, click button 6 times:
Back to Mainactivity, you can see that UpdateUI () is triggered, showing the number of clicks of activity 2:
Android Event Bus