0

Problem:
For some communication scenarios I am using EventBus. I have got an event that is already successfully fired and subscribed by different components in my app. Now I need an activity to subscribe that event. Unfortunately it is not reached.

Question:
How can I achieve that the activity does subscribe the event correctly, either? Is the problem with registering the activity?

Note:
I have found that post that suggests to use onStart() and onStop() events.

my activity class:

public class MachineActivity extends AppCompatActivity{

  (...)

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

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

  @Subscribe(threadMode = ThreadMode.MAIN)
  public void characteristicsChangeByUser(IntentChangeByUser intentChangeByUser) {
    // Do something here.
  }

  (...)
}

EventBus class:

public class IntentChangeByUser {

  int position;
  int value;

  public IntentChangeByUser(int position, int value){
    this.position = position;
    this.value = value;
  }

  public int getPosition() {
    return position;
  }

  public int getValue() {
    return value;
  }
}
Community
  • 1
  • 1
jublikon
  • 3,427
  • 10
  • 44
  • 82

1 Answers1

1

Could be because you have the wrong way to unregister then EventBus in onStop().
Change to this:

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

@Override
public void onStop() {
   EventBus.getDefault().unregister(this);
    super.onStop();
}

Then make sure in your Subscriber Activity, there is received Event:

@Subscribe(threadMode = ThreadMode.MAIN)
public void characteristicsChangeByUser(IntentChangeByUser intentChangeByUser) {
  // Do something here.
  Log.d("Activity", "IntentChangeByUser Event received");
}
ישו אוהב אותך
  • 28,609
  • 11
  • 78
  • 96