Android EventBus实战
Android EventBus实战
EventBus有四个要素:发布者,订阅者,事件,总线,发布者通过总线发布事件,订阅者接收事件
EeventBus源码地址: http://greenrobot.org/eventbus/
实战源码
一、在第一个Activity里面注册EventBus,并发布时间给当前Activity. 二、在第二个Activity里面发送消息,在第一个Activity里面接收并显示
事件:
public class MyEvent {
private String content;
public MyEvent(String content){
this.content = content;
}
public String getContent(){
return content;
}
}
MainAcitivity,在oncreate里面注册EventBus,在onDestroy取消注册,编写接收事件函数:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//注册EventBus
EventBus.getDefault().register(this);
}
public void startSecond(View view){
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
@Override
public void onDestroy(){
EventBus.getDefault().unregister(this);
}
//接收事件
@Subscribe
public void onEventMainThread(MyEvent MyEvent){
Toast.makeText(this, MyEvent.getContent(), Toast.LENGTH_SHORT).show();
}
public void passSelf(View view){
//取消注册
EventBus.getDefault().post(new MyEvent("传递给当前线程"));
}
}
SecondActivity, 发布时间给MainAcitivity
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
public void passOther(View view) {
EventBus.getDefault().post(new MyEvent("传递消息给其他线程"));
}
}
注意:
a. 发布者和订阅者的事件类型必须一样
b. 在onEventMainThread之前必须使用@Subscribe