1、引入依赖:
implementation 'org.greenrobot:eventbus:3.1.1'
2、编写消息载体
public class MessageEventBus {
private String mMsg;
public MessageEventBus(String mMsg) {
this.mMsg = mMsg;
}
public MessageEventBus() {
}
public String getmMsg() {
return mMsg;
}
public void setmMsg(String mMsg) {
this.mMsg = mMsg;
}
}
3、编写EventBus要注册的类,哪需要接收哪就注册onCreate(),已经反注册在onDestory()里声明。
public class MainActivity extends AppCompatActivity {
private Button button;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.btn_try);
tv = (TextView)findViewById(R.id.tv);
EventBus.getDefault().register(this);//EventBus注册代码
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
SecondAcitivity.class);
startActivity(intent);
}
});
}
@Subscribe
public void onEventMainThread(MessageEventBus event) {
String msg = "onEventMainThread收到了消息:" + event.getmMsg();
Log.d("harvic", msg);
tv.setText(msg);
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
protected void onDestroy(){
super.onDestroy();
EventBus.getDefault().unregister(this);//反注册EventBus
}
}
4、实现发送的类
public class SecondAcitivity extends Activity {
private Button btn_FirstEvent;
private MessageEventBus messageEventBus;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_acitivity);
btn_FirstEvent = (Button) findViewById(R.id.btn_first_event);
btn_FirstEvent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
messageEventBus = new MessageEventBus();
messageEventBus.setmMsg("123");
//发送发放 EventBus.getDefault().post();
EventBus.getDefault().post(
messageEventBus);
}
});
}