Android:绿色机器人事件总线:单个帖子收到多个事件

时间:2015-07-25 07:08:53

标签: android greenrobot-eventbus

我在Android中使用绿色机器人事件总线

我使用EventBus.getDefault()调用所有事件.post和onStop我调用EventBus.getDefault()。unregister(this);在我的活动中。然而,一旦我按下并重新打开应用程序,在单个事件帖子上,会收到多个onEvent()。还有其他人遇到过这个问题吗?

@Override
protected void onStart() {
    super.onStart();
    getBus().register(this);
}

@Override
protected void onPause() {
    getBus().unregister(this);
    super.onPause();
}

@Override
protected void onStop() {
    getBus().unregister(this);
    super.onStop();
}


protected EventBus getBus() {
    return EventBus.getDefault();
}

1 个答案:

答案 0 :(得分:5)

我弄明白了这个问题。每次app从后台返回时,都会再次调用register函数。与我错误的假设相反,绿色机器人没有管理重复,我需要在注册之前添加一个检查。所以这是我的最终代码的样子。

mBus = EventBus.getDefault();

void registerAndCheck(Object helper)
{
    if(!mBus.isRegistered(helper))
    {
        mBus.register(helper);
    }
}


mFileHelper = new FilesHelper();
registerAndCheck(mFileHelper);

希望它有所帮助。