//第一步先要注入依赖
//第一个anctivity跳转到第二个页面然后第二个页面给第一个页面发送一个消息有注册就有解绑没有解绑的话会出现错误
public class MainActivity extends AppCompatActivity { private Button but; private TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //第二步接收消息页面注册 setContentView(R.layout.activity_main); EventBus.getDefault().register(this); but = (Button) findViewById(R.id.btn_tyy); tv = (TextView) findViewById(R.id.tv); but.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent it = new Intent(getApplicationContext(), Main2Activity.class); startActivity(it); } }); } @Override protected void onStart() { super.onStart(); } @Override protected void onDestroy() { //在生命周期的最后生命周期销毁时要解除绑定 super.onDestroy(); EventBus.getDefault().unregister(this); } @Subscribe(threadMode = ThreadMode.MAIN) public void onEventMainThread(Event event){ String msg="接受到了消息"+event.getMsg(); Log.d("harvic",msg); tv.setText(msg); Toast.makeText(this,msg,Toast.LENGTH_SHORT).show(); } }
//定义一个接口用来传值
public class Event { private String Mmsg; public Event(String msg){ Mmsg=msg; } public String getMsg(){ return Mmsg; } }//第二个发送的activity
public class Main2Activity extends AppCompatActivity { private Button butsecond; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); butsecond = (Button) findViewById(R.id.first); butsecond.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { EventBus.getDefault().post(new Event("aaaaaaaaaaaaaaa")); } }); } }