2

I have a foreground service and an activity which communicates with it. The service is started and stopped by the activity, but can also stop by itself.

The service should remain running until explicitly stopped, even if the user navigates away from the service. In many ways, this scenario is similar to a music player.

If the service is not actually in use, it would be good if it could still hang around until the system needs memory, like a paused activity does.

How should the activity communicate with the service? I have considered:

  • Bind the service, and obtain a reference to the service through the binder. This would stop the service if the activity is destroyed.
  • Start the service. Have the service store a reference in a static field. Have the activity wait for the service to start and then use the reference. This feels hacky.
  • Start the service, then bind the service, and obtain a reference to the service through the binder. This works, but causes the service to be restarted every time it's killed, as if it was sticky.
  • Start the service, then send intents to it (using startService). This sounds inefficient, but I haven't measured it, so maybe it's okay. It doesn't allow the service to notify the activity of updates.
  • Start the service, the bind the service. Make sure the service is always explicitly stopped when its work is done. This does mean the service won't "hang around until the system needs memory". Additionally, it needs to save its data somewhere other than its own fields, because the user might go back to the activity immediately after the service is stopped.
  • Remove the service from the equation by merging it into the activity. Do something else to keep the TCP connection open.
user253751
  • 57,427
  • 7
  • 48
  • 90

1 Answers1

0

For message passing android provides Handler,Messenger. You might want to take a look at the following link and I think that it will satisfy your needs.

Example: Communication between Activity and Service using Messaging

Community
  • 1
  • 1
upenpat
  • 685
  • 3
  • 12