如何做一个服务,它的活动沟通?如何服务调用方法的活动,它启动的服务? [英] How does a Service communicate with its Activity? How can a Service call a method in the Activity, which started that Service?
问题描述
假设我有一个活动,这是一个列表。它调用一个服务时,该活动开始。该服务会做背景的东西 - 下载,分析,并填写列表
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.
我的问题是:如何能与活动在服务通信? 我怎样才能在活动调用一个方法,从服务? (我是新来的OOP)
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)
该服务已启动这样的:
hello_service = new Intent(this, HelloService.class);
startService(hello_service);
我的一个服务做的一件事情就是下载和解析XML。在此之后,它需要填充列表!所以,我想通过解析的东西,回到活动,并在活动调用一个方法来填补这个列表中。
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.
推荐答案
最近,我问了一个非常类似的问题,<一个href="http://stackoverflow.com/questions/2274641/best-way-for-service-that-starts-activity-to-communicate-with-it/">best方式为服务启动活动与它沟通,这有一个非常有用的答案。
I recently asked a very similar question, best way for service that starts activity to communicate with it, that got a very helpful answer.
此外,考虑使用的AsyncTask
,而不是一个服务,如果该服务不需要活着活动时关闭。然后,你不必费心与服务器/活动的通信。
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.
这篇关于如何做一个服务,它的活动沟通?如何服务调用方法的活动,它启动的服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!