EventBus is a publish/subscribe event bus optimized for Android.
so make it simple,just think EventBus as a framework that allow different compoents to communicate,
usually a subscribe register a certain event,then whenever a publisher has post an event,any subscribes who had register this event will be able to receive the notify.
This is an example,Let's say MainActivity is a subscribe who has register to receive RecvEvent event,
And Second Activity is a publicer who will post a RecvEvent when his btn is clicked.Theoretically speaking,MainActivity is able to recevie the event that posted by SecondActivity.
//Event
public class RecvEvent
{
private final String info;
public RecvEvent(String info)
{
this.info = info;
}
public String getInfo()
{
return info;
}
}
//Subscribe:MainActivity
public class MainActivity extends AppCompatActivity {
private TextView tvShowInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvShowInfo = (TextView)findViewById(R.id.tvShowRecv);
//register to recevie ShowRecvEvent event
EventBus.getDefault().register(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
//destroy res
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onRecvEvent(ShowRecvEvent event)
{
tvShowInfo.setText(event.getInfo());
}
public void onJump(View view)
{
startActivity(new Intent(this,SecondActivity.class));
}
}
//publisher:SecondActivity
public class SecondActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
}
public void onSend(View view)
{
EventBus.getDefault().post(new ShowRecvEvent("this is from second activity"));
}
}