Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data from a service thats already running?

Tags:

android

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

like image 779
arber Avatar asked May 21 '11 19:05

arber


2 Answers

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)

like image 169
PwC Avatar answered Oct 25 '22 08:10

PwC


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.

like image 45
CommonsWare Avatar answered Oct 25 '22 08:10

CommonsWare