Can I use greenrobot EventBus for Communication between Activity and Service?

Bincy Baby picture Bincy Baby · Sep 28, 2015 · Viewed 13k times · Source

EventBus Can I use this library for Activity to Service communication ?

I have tried this in my app as follows:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    EventBus.getDefault().register(this);
    setContentView(R.layout.activity_music_player);
    Intent serviceIntent=new Intent(MusicPlayerActivityTest.this,MusicPlayerServiceTest.class);
    startService(serviceIntent);
    EventBus.getDefault().post(new SetSongList(songArraList, 0));
}
@Override
protected void onDestroy() {
    EventBus.getDefault().unregister(this);
    super.onDestroy();
}

and in my service onEvent called

Answer

Anthony picture Anthony · Oct 27, 2015

You have to register the Subscriber, not the emitter.

So, remove register/unregister from your app if you do expect to get the event. If so, just add the onEvent (AnyEvent event) method to the Application class.

Then register EventBus in your service in onStart() and unregister in onStop().

It should work better then.

In your Application

public class MyApp extend Application {
  @Override
  public void onCreate() {
    super.onCreate();
    ...
    EventBus.getDefault().post(new SetSongList(songArraList, 0));
  }
}

or in your Activity

public class MyActivity extend Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...
    EventBus.getDefault().post(new SetSongList(songArraList, 0));
  }
}

and in your Service

public class MyService extends Service {
  ...
  @Override
  public void onCreate() {
    super.onCreate();
    EventBus.getDefault().register(this);
  }

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

  public void onEvent(SetSongList event){
    // do something with event
  }
  ...
}