EventBus是一个Android端优化的publish/subscribe消息总线,简化了应用程序内各组件间、组件与后台线程间的通信。比如请求网络,等网络返回时通过Handler或Broadcast通知UI,两个Fragment之间需要通过Listener通信,这些需求都可以通过EventBus实现。
作为一个消息总线,有三个主要的元素:
每个事件订阅函数都是和一个`ThreadMode`相关联的,ThreadMode指定了会调用的函数。有以下四个ThreadMode:
根据事件订阅都函数名称的不同,会使用不同的ThreadMode,比如果在后台线程加载了数据想在UI线程显示,订阅者只需把函数命名为onEventMainThread。
定义事件类型:
public class MyEvent {}
定义事件处理方法:
public void onEventMainThread
注册订阅者:
EventBus.getDefault().register(this)
发送事件:
EventBus.getDefault().post(new MyEvent())
public class MainActivity extends ActionBarActivity { private ConditionVariable mConditionVariable; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mConditionVariable = new ConditionVariable(); EventBus.getDefault().register(this); initUI(); startActivity(new Intent(this, TwoActivity.class)); new Thread(new SleepThread()).start(); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } TextView mTxtOne; private void initUI() { mTxtOne = (TextView) findViewById(R.id.txt_one); } public void onEventMainThread(EventOne eventOne) { Log.i("MainActivity", "MainActivity,,,onEventMainThread"); mTxtOne.setText(eventOne.getString()); } // public void onEventAsync(EventOne eventOne) { // Log.i("MainActivity", "onEventAsyc--->" + Thread.currentThread().getName()); // } // // public void onEventBackgroundThread(EventOne eventOne) { // Log.i("MainActivity", "onEventBackgroundThread--->" + Thread.currentThread().getName()); // } // public void onEventPostThread(EventOne eventOne) { // Log.i("MainActivity", "onEventPostThread--->" + Thread.currentThread().getName()); // } class SleepThread implements Runnable { @Override public void run() { Log.i("Activity", "MainActivity,,,SleepThread--->begin"); mConditionVariable.block(2000); Log.i("Activity", "MainActivity,,,SleepThread--->end"); EventBus.getDefault().post(new EventOne("11111")); } } }
EventOne代码:
public class EventOne { String string; public EventOne(String string) { this.string = string; } public String getString() { return string; } }