views:

64

answers:

2

Suppose I have an Activity that's a list. It calls a Service when this Activity starts. The Service will do background stuff--download, parse, and fill the list.

My question is this: How can the Service communicate with the Activity? How can I call a method in the Activity, from the Service? (I'm new to OOP)

The Service is started like this:

hello_service = new Intent(this, HelloService.class);
startService(hello_service);

One of the things my service does is download and parse an XML. After that, it needs to fill a list! So, I want to pass the parsed stuff back to the Activity, and call a method in the Activity to fill that list.

+1  A: 

I recently asked a very similar question that got a very helpful answer:

http://stackoverflow.com/questions/2274641/best-way-for-service-that-starts-activity-to-communicate-with-it

Also, consider using AsyncTask instead of a service if the service dont need to be alive when the activity is closed. Then you dont need to bother with the server/activity-communication.

sandis
A: 

You can set activity object to service and invoke methods of your activity from service. But you must to care about thread-safe when you update your UI.

Hope this helps! Tutorial

Yeti
What does "set activity object to service" mean?
TIMEX
In service you create static method smth like this:public static void setMainActivity(YourActivityType activity) { YOUR_ACTIVITY = activity;}and then, before invoke startService() method just call YourService.setMainActivity(this) from your activity.
Yeti
Thanks. It maeks sense. But what about thread-safe? Why would this not be safe?
TIMEX
UI and service run in separate threads. If you want to change UI from service thread you must to take care bout thread safety.
Yeti