Search code examples
javaandroidevent-busgreenrobot-eventbus

EventBus multiplying messages by count of Activities


I'm using greenrobot EventBus and have some misunderstandings how to use it.

In my app, I have 4 activities: MainActivity and 3 other. Each Activity have it's own role in app, and MainActivity holds connection via COM port and sends/receives messages. So, when message is received, it sends via EventBus to current working activity. And when other Activity needs to sent message to COM port, it sending message to MainActivity via EventBus too. Problem is that when I'm working in one activity - all works fine, but when I try to do something in other activities - messages from EventBus are duplicaed. There is more - when I try to work in third activity - message is multiplies by 3 and so on.

Here some code:

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

This method I use to send message to another Activity from MainActivity

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

And catch event from other Activities in MainActivity

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

As you can see, I'm unregistering onPause() and registering onResume(), but when I'm closing this activity and starting it again messages are duplicating.

Example:

1st use:

    55017031011_TURN_STRAIGHT27

2nd use:

    55017031011_TURN_STRAIGHT2755017031011_TURN_STRAIGHT27

I have readed gitHub issues, but not found any answer.

And sorry for mistakes.


Solution

  • Unregister MainActivity from MessageEventFromIntent event after the activity is closed.