I have a service that runs once the app starts and I was wondering how can I get data from that service to an activity at anytime without having to restart the service
No offense, but the "Messenger" and "binding" way kept me busy for about 2 days to figure out. Not that it's wrong, but it overcomplicated things for me.
In my opinion its easier for a service to broadcast the data so that an Activity can just access the data when available. Do the tutorial on this link: http://www.websmithing.com/2011/02/01/how-to-update-the-ui-in-an-android-activity-using-data-from-a-background-service/comment-page-1/#comment-734
(took me 10minutes to figure out and implement... excellent tutorial)
If the service is already running, calling startService()
does not "restart the service". It simply sends a command to be picked up by the service in onStartCommand()
. So, you can send a command that triggers the service to do something on the activity's behalf, which could involve communications from the service back to the activity (e.g., via a Messenger
).
Or, as @Tom Dignan points out, you can bind to the service. Just be a bit careful as you deal with configuration changes, like when the user rotates the screen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With