I have implemented EventBus in my project but I am not getting all of my events
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.btn);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EventBus.getDefault().post(new MessageEvent());
EventBus.getDefault().post(new MessageEvent2());
}
});
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event)
{
Toast.makeText(this, "MainActivity called", Toast.LENGTH_SHORT).show();
};
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
}
Here i created 2 event inside onClick(); And this is my AnotherActivity where i have another @Subscribe
public class AnotherActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent2 event2)
{
Toast.makeText(this, "AnotherActivity called", Toast.LENGTH_SHORT).show();//Not getting called
};
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
}
I dont know why my second toast is not getting called, i have done every thing correctly.
What i suspect is the AnotherActivity
is not created yet so my event is not called is that is so what is use of EventBus then?
Yes, if the event happened in past and the component(activity) is not active/created then the event will not be received.
You can use Sticky Event to listen to past events in newly created activity
so use
postSticky
and add
sticky = true
insubscribe
annotationor you can receive them manually
or remove it from history as well