简体   繁体   English

服务如何与其活动进行通信? 服务如何调用活动中启动该服务的方法?

[英]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. 该服务将执行后台工作-下载,解析并填写列表。

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) (我是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. 我的服务要做的一件事是下载并解析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. 因此,我想将已解析的内容传递回Activity,并在Activity中调用一个方法来填充该列表。

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. 另外,如果在活动关闭时不需要AsyncTask服务,请考虑使用AsyncTask代替服务。 Then you don't need to bother with the server/activity-communication. 然后,您不必费心服务器/活动通信。

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. 但是,在更新UI时,您必须关心线程安全。

Hope this helps! 希望这可以帮助! Tutorial 教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM