EventBus detailed usage tutorial [Post in Activity, Service, Referer], eventbusreceiver
Add EventBus
compile 'de.greenrobot:eventbus:2.4.0'
Or
Download the jar package directly | click to download
Register and log out of EventBus
@ Override protected void onStart () {super. onStart (); // register EventBus. getDefault (). register (this); Logger. e ("EventBus registration") ;}@ Override protected void onStop () {super. onStop (); // cancel EventBus. getDefault (). unregister (this); Logger. e ("EventBus logout ");}
Custom Message Type
public class MessageEvent { public String message; public MessageEvent(String message){ this.message=message; }}
Create message acceptance
// The place where messages are received (in the Android UI thread) public void onEventMainThread (MessageEvent event) {Logger. e ("onEventMainThread" + event. message); TV _demo.setText (event. message );}
Post message
1. Send a message to the Activity in the Child thread to update the UI
Class MyThread extends Thread {@ Override public void run () {// send the message EventBus. getDefault (). post (new MessageEvent ("this is the message update UI sent by EventBus "));}};
2. Send a message in the Service to update the UI of the Activity.
Public class MyService extends Service {public static final String ACTION_START = "ACTION_START"; @ Override public IBinder onBind (Intent intent) {return new Binder ();} @ Override public int onStartCommand (Intent intent, int flags, int startId) {if (ACTION_START.equals (intent. getAction () {new MyServerThread (). start ();} return super. onStartCommand (intent, flags, startId);} class MyServerThread extends Thread {@ Override public void run () {EventBus. getDefault (). post (new MessageEvent ("this is the Post message in the MyServerThread thread of MyService "));}}}
3. Send a message to the Activity to update the UI in the worker er.
Public class MyBroadcastReceiver extends BroadcastReceiver {public static final String ACTION_SEND = "ACTION_SEND"; @ Override public void onReceive (Context context, Intent intent) {if (ACTION_SEND.equals (intent. getAction () {EventBus. getDefault (). post (new MessageEvent ("this is a message sent to Activity in [Broadcast "));}}}
Github address | welcome to Star