0

There's previous questions similar to this, for example here: How to have Android Service communicate with Activity

But in the accepted answer to that question, the answer relies on the fact the activity is creating the service. However my question in that case is what to do if the activity does not create the service?

People will say follow the unaccepted answer in that same question (the one with lots of upvotes), which is for the service to broadcast to the Activity.

BUT my question is, what if the activity wants to know the current value of something in the service at the point the activity is created, rather than wait until the service broadcasts when that value changes?

Community
  • 1
  • 1
Gruntcakes
  • 37,738
  • 44
  • 184
  • 378

1 Answers1

0

what if the activity wants to know the current value of something in the service at the point the activity is created, rather than wait until the service broadcasts when that value changes?

Use an event bus.

For example, greenrobot's EventBus supports sticky events. When your activity registers for the sticky event, it is immediately handed the last event of that type that had been sent out, plus future ones.

Or, Square's Otto supports the @Producer annotation. When your activity registers for an event supported by a @Producer, it immediately gets the value that the @Producer produces, plus future events.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491