【问题标题】:EventBus multiplying messages by count of ActivitiesEventBus 将消息乘以活动计数
【发布时间】:2017-06-21 16:30:07
【问题描述】:

我在使用greenrobot EventBus,对如何使用有一些误解。

在我的应用中,我有 4 个活动:MainActivity 和其他 3 个。每个 Activity 在应用程序中都有自己的角色,MainActivity 通过 COM 端口保持连接并发送/接收消息。因此,当收到消息时,它会通过 EventBus 发送到当前工作活动。而当其他Activity需要向COM口发送消息时,它也通过EventBus向MainActivity发送消息。问题是当我在一项活动中工作时 - 一切正常,但是当我尝试在其他活动中做某事时 - 来自 EventBus 的消息是重复的。还有更多 - 当我尝试在第三个活动中工作时 - 消息乘以 3 等等。

这里有一些代码:

public class ManualControl extends AppCompatActivity 
{
 @Override
 protected void onCreate(Bundle savedInstanceState) 
 {
     super.onCreate(savedInstanceState);
     //my other code here
 }

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

 @Override
 public void onResume()
 {
     super.onResume();
     EventBus.getDefault().register(this);
 }

 @Subscribe(threadMode = ThreadMode.MAIN)
 public void onEvent(MessageEventFromMain event)
 {
  //code to do when get message from MainActivity
 };    

 private void sendMessage(String messageID, String messageName)
 {
     EventBus.getDefault().post(new MessageEventFromIntent(messageID, messageName));
 }
}

我用来从 MainActivity 向另一个 Activity 发送消息的方法

    EventBus.getDefault().post(new MessageEventFromMain(messageFromSerial));

并从 MainActivity 中的其他活动捕获事件

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEventFromIntent(MessageEventFromIntent event)
    {
     //code to do when get message from intent
    }

如您所见,我正在取消注册 onPause() 并注册 onResume(),但是当我关闭此活动并再次启动它时,消息会重复。

例子:

第一次使用:

    55017031011_TURN_STRAIGHT27

第二次使用:

    55017031011_TURN_STRAIGHT2755017031011_TURN_STRAIGHT27

我已经阅读了 gitHub 问题,但没有找到任何答案。

对错误深表歉意。

【问题讨论】:

  • 我怀疑问题是当我打开 Activity 并尝试发送消息时,它正在通过“new MessageEventFromIntent”方法创建新的 MessageEventFromIntent 对象,而不是在 Activity 关闭时将其删除。
  • 所以我需要对这个对象做空引用,所以垃圾收集器可以删除它。但是怎么做? Activity 关闭后从 MessageEventFromIntent 事件中注销 MainActivity?
  • 是的,确实有问题!刚刚检查了 HPROF 查看器显示。 Screen Shot

标签: java android event-bus greenrobot-eventbus


【解决方案1】:

在活动关闭后从MessageEventFromIntent事件中注销MainActivity

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多