public class Activity1 extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
final MyEvent event = new MyEvent();
event.data = "消息携带的数据";
event.otherData = 123;
Log.i("Activity1", "发送事件:"+Thread.currentThread().getId());
EventBus.getDefault().post(event);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException ignore) {
}
Log.i("Activity1", "发送事件:"+Thread.currentThread().getId());
EventBus.getDefault().post(event);
}
}).start();
}
* 接收事件和post事件在同一个线程中执行
* @param event 消息体
*/
@Subscribe(threadMode = ThreadMode.POSTING)
public void onEvent(MyEvent event){
Log.i("Activity1", "onEvent:"+Thread.currentThread().getId());
}
* 接收事件永远在UI线程中执行
* @param event 消息体
*/
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(MyEvent event){
Log.i("Activity1", "onEventMainThread:"+Thread.currentThread().getId());
}
* 如果在子线程中post事件,则会在相同子线程接收
* 如果在UI线程中post事件,则会启动一个子线程接收事件
* @param event 消息体
*/
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onEventBackgroundThread(MyEvent event){
Log.i("Activity1", "onEventBackgroundThread:"+Thread.currentThread().getId());
}
* 新建一个子线程来接收事件
* @param event 消息体
*/
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onEventAsync(MyEvent event){
Log.i("Activity1", "onEventAsync:"+Thread.currentThread().getId());
}
}