compile 'org.greenrobot:eventbus:3.0.0'
public class MessageEvent{ private String message; public MessageEvent(String message){ this.message=message; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
分別在FirstActivity的onCreate()方法和onDestory()方法裏,進行註冊EventBus和解除註冊。java
//接收activate public class FirstActivity extends AppCompatActivity { private Button mButton; private TextView mText; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.first_activity); mButton = (Button) findViewById(R.id.btn1); mText = (TextView) findViewById(R.id.tv1); mText.setText("今天是星期三");
//在須要訂閱事件的地方註冊事件 EventBus.getDefault().register(this); jumpActivity(); } //點擊事件 private void jumpActivity() { mButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(FirstActivity.this,SecondActivity.class); startActivity(intent); } }); } //接收 @Subscribe(threadMode = ThreadMode.MAIN) public void Event(MessageEvent messageEvent) { mText.setText(messageEvent.getMessage()); } //銷燬 @Override protected void onDestroy() { super.onDestroy(); if(EventBus.getDefault().isRegistered(this)) { EventBus.getDefault().unregister(this); } } }
在這裏,事件的處理線程在主線程,是由於,我要讓TextView去顯示值。
在 SecondActivity裏去進行事件的發送。(發送活動)bash
public class SecondActivity extends AppCompatActivity { private Button mButton2; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.second_activity); mButton2=(Button) findViewById(R.id.btn2); jumpActivity(); } private void jumpActivity() { mButton2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {
//發送 EventBus.getDefault().post(new MessageEvent("歡迎你們瀏覽我寫的博客")); finish(); } }); } }