eventBus的使用步骤:
//在Activity中,注册和反注册
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this); //第1步: 注册
}
@Override protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);//反注册
}
//在注册了的Activity中,声明处理事件的方法
//第2步:注册一个在后台线程执行的方法,用于接收事件
@Subscribe(threadMode = ThreadMode.BackgroundThread)
public void onUserEvent(ClassEvent event) {
//参数必须是ClassEvent类型, 否则不会调用此方法
}
//在任意地方,调用发送事件
EventBus.getDefault().post(new ClassEvent());//第3步: 发送事件
//在任意地方,注册事件类
class ClassEvent{} //定义一个事件, 可以不包含成员变量,和成员方法
新版本的eventBus的使用,接收数据的回调方法变成了这样:
@Subscribe(threadMode = ThreadMode.MainThread) //在ui线程执行 public void onUserEvent(UserEvent event) { }
@Subscribe(threadMode = ThreadMode.BackgroundThread) //在后台线程执行 public void onUserEvent(UserEvent event) { }
@Subscribe(threadMode = ThreadMode.Async) //强制在后台执行 public void onUserEvent(UserEvent event) { }
@Subscribe(threadMode = ThreadMode.PostThread) //默认方式, 在发送线程执行 public void onUserEvent(UserEvent event) { } 举个例子,用eventBus代替handler,实现秒表:
public class MainActivity extends AppCompatActivity { private TextView mTextView; private int time = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EventBus.getDefault().register(this); mTextView = (TextView) findViewById(R.id.tv_showtime); mTextView.setText(0 + ""); getTime(); } private void getTime() { new Thread(new Runnable() { @Override public void run() { try { time++; Thread.sleep(1000); EventBus.getDefault().post(new FirstEvent(time + "")); } catch (InterruptedException e) { e.printStackTrace(); } } }).start(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onUseEvent(FirstEvent event) { boolean isMainThread = Thread.currentThread() == Looper.getMainLooper().getThread(); Log.i("xyz", "" + isMainThread); mTextView.setText(event.getMsg()); getTime(); } } |
其中FirsrtEvent就是简单的一个实体类:
public class FirstEvent { private String mMsg; public FirstEvent(String msg) { // TODO Auto-generated constructor stub mMsg = msg; } public String getMsg(){ return mMsg; } } |