gpt4 book ai didi

android - Eventbus onMessageEvent 没有被调用

转载 作者:行者123 更新时间:2023-11-29 01:02:33 25 4
gpt4 key购买 nike

我已经在我的项目中实现了 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);
}
}

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

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

最佳答案

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

是的,如果事件发生在过去并且组件( Activity )未激活/创建,则不会接收到该事件。

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}

关于android - Eventbus onMessageEvent 没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50074788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com