事件總線這個其實沒什麼好說的,除了已經ondestroy的fragment或者activity不能接受外,只要定義了的都能接收消息
代碼以下,須要注意的一點就是接收的監聽事件必須用public修飾而且加上@Subscribe註解ide
compile 'org.greenrobot:eventbus:3.0.0'
public class MainActivity extends Activity { private TextView textView; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.tv); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(); intent.setClass(MainActivity.this, SecondActivity.class); startActivity(intent); } }); EventBus.getDefault().register(this); } @Subscribe public void onMessageEvent(MessageEvent messageEvent){ textView.setText(messageEvent.getMessage()); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }
public class SecondActivity extends AppCompatActivity { private TextView tv_receive; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); tv_receive = findViewById(R.id.tv_receive); tv_receive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { EventBus.getDefault().post(new MessageEvent("發送成功")); finish(); } }); } @Override protected void onDestroy() { super.onDestroy(); } }
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; } }