How does a Service communicate with its Activity?

2019-07-15 01:07发布

问题:

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:

I recently asked a very similar question, best way for service that starts activity to communicate with it, that got a very helpful answer.

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



回答2:

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