Eventbus onMessageEvent 没有被调用

Eventbus onMessageEvent not getting called

我已经在我的项目中实现了 EventBus,但是我没有得到我的所有事件

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);
    }
}

这里我在 onClick() 中创建了 2 个事件; 这是我的 AnotherActivity,我有另一个 @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);
    }
}

我不知道为什么我的第二个吐司没有被调用,我已经正确地完成了每件事。

我怀疑 AnotherActivity 还没有创建,所以我的事件没有被调用,那 EventBus 有什么用?

What i suspect is the AnotherActivity is not created yet so my event is not called is that is so

是的,如果事件发生在过去并且组件(activity)不是active/created那么事件将不会被接收。

what is use of EventBus then?

您可以使用Sticky Event在新创建的activity

中收听过去的事件

所以使用postSticky

EventBus.getDefault().postSticky(new MessageEvent2());

并在subscribe注释中添加sticky = true

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent2 event2){
    Toast.makeText(this, "AnotherActivity called", Toast.LENGTH_SHORT).show();//Not getting called
};

或者您可以手动接收它们

MessageEvent2 msg2 = EventBus.getDefault().getStickyEvent(MessageEvent2.class);
// you can also remove it using
// EventBus.getDefault().removeStickyEvent(msg2);

或者也将其从历史记录中删除

MessageEvent2 msg2 = EventBus.getDefault().removeStickyEvent(MessageEvent2.class);
if(msg2!=null){//do something}