2

I am trying to receive a sticky event in an IntentService. I have tried catching the events in onEvent()and onEventBackgroundThread() but I don't receive events. I know how to send and receive events between activities and fragments unable to get sending events to a service to work. Does the eventbus post to a service? If it does where to subscribe for the events? I tried subscribing in the onHandleIntent(Intent intent) and in the constructor of the Service. No Luck. Can someone please help out?

iZBasit
  • 1,314
  • 1
  • 15
  • 30
  • Did you manage to find out how to do this in an IntentService? – Bootstrapper Jun 14 '15 at 22:44
  • 2
    IntentService is supposed to only do one thing.Meaning that it is created as soon as it has something to do (onHandleIntent) and is destroyed when it has nothing left to do. If you want something more flexible, use a Service instead of IntentService. – Simon Marquis Jun 22 '15 at 07:33
  • see here [http://developer.android.com/training/run-background-service/report-status.html](http://developer.android.com/training/run-background-service/report-status.html). Is this you want? – huangming Jun 22 '15 at 11:17

2 Answers2

4

Services and EventBus don't really mix. An IntentService is intended to do something in a background thread - fire and forget. Services can run in different processes and use different Context's. The way they communicate is very proprietary and doesn't lend itself well to external frameworks like EventBus.

My advice is to reconsider the need for the IntentService and consider using http://greenrobot.org/eventbus/documentation/delivery-threads-threadmode/ different delivery methods, so post an event from your UI to a manager in your comms layer who will receive it on a background thread, process it, and in turn post another event with the results, which the UI will listen for on the main thread.

So your manager looks something like this:

@Subscribe(threadMode = ThreadMode.BackgroundThread)
public void onEvent(AccountsDoGetEvent event){
    //do long running task like going to network or database
    EventBus.getDefault().post(new AccountsUpdatedEvent);
}

and your fragment looks something like this:

@Subscribe(threadMode = ThreadMode.MainThread)
public void onEvent(AccountsUpdatedEvent event){
    //update the UI
}

public void onButtonClicked(){
    EventBus.getDefault().post(new AccountsDoGetEvent());
}
shredder
  • 1,438
  • 13
  • 12
0

You need to register your service using 'registerSticky' to catch sticky events

guy.gc
  • 3,359
  • 2
  • 24
  • 39