———————-基本使用————————-
导包
compile 'org.greenrobot:eventbus:3.0.0'
注册
在需要接收事件的activity中注册消息和反注册消息
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
setContentView(R.layout.activity_main);
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
发起事件
自定义一个类,用于传递数据和区分响应对象
public class Event {
private String mMsg;
public Event(String msg) {
mMsg = msg;
}
public String getMsg(){
return mMsg;
}
}
在第二act中发起消息
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void click(View view) {
EventBus.getDefault().post(new Event("昨日一去不复回"));
}
}
在已经订阅的页面提供一个方法响应消息
public class MainActivity extends AppCompatActivity {
private TextView tv_main_act;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
initView();
}
private void initData() {
EventBus.getDefault().register(this);
}
private void initView() {
tv_main_act = (TextView) findViewById(R.id.tv_main_act);
}
public void jump(View view) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
@Subscribe
public void onGetEvent(Event event) {
String msg = "onEventMainThread收到了消息:" + event.getMsg();
tv_main_act.setText(msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
@Override
protected void onDestroy() {
EventBus.getDefault().unregister(this);
super.onDestroy();
}
}
———————-进阶使用————————
EventBus的线程模式
EventBus中的线程概念分为四种:
MainThread
BackgroundThread
PostThread
Async
在注解中指定运行的线程
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onEventBackgroundThread(Event2 event) {
Log.v("meee",getClass()+":\n"+"子线程中响应:"+event.getMsg()+(Looper.myLooper()!=Looper.getMainLooper()));
}
粘性事件
所谓的粘性事件,就是指在事件发起之后在注册的页面也可以接收到事件
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
在该注解下的方法,即使粘性事件被发起前没有注册,注册后仍然可以接收到事件,但只能接收到发起的最后一个粘性事件
public void click2(View view) {
EventBus.getDefault().postSticky(new Event2("昨日一去不复回"));
}
public class MainActivity extends AppCompatActivity{
oncreate(){
EventBus.getDefault().register(this);
}
@Subscribe(sticky = true)
public void onEventBackgroundThread(Event2 event) {
Log.v("meee",getClass()+":\n"+"粘性事件响应");
}
}