在Android中:如何调用服务的活动功能? [英] In Android: How to Call Function of Activity from a Service?

查看:227
本文介绍了在Android中:如何调用服务的活动功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动(A)和服务(S),由A开始,像这样:

I have an Activity (A) and a Service (S) which gets started by A like this:

Intent i = new Intent();
i.putExtra("updateInterval", 10);
i.setClassName("com.blah", "com.blah.S");
startService(i);

A在A中有这样的功能:

A have a function like this one in A:

public void someInfoArrived(Info i){...}


$ b b

现在我想从S.内部调用A.someInfoArrived(i)。
Intent.putExtra没有可以传递对象引用的版本...
请帮助!

Now I want to call A.someInfoArrived(i) from within S. Intent.putExtra has no version where I could pass an Object reference etc ... Please help!

PS:另一种方法(A轮询S的新信息)不是我需要的。我发现了足够的信息,如何做到这一点。

PS: The other way around (A polling S for new info) is NOT what I need. I found enough info about how to do that.

推荐答案

一个选项是从 startService()切换到 bindService()并使用本地绑定模式。然后,你需要在S上调用一个方法来注册一个监听器或回调方法。然后,S将有一些东西,当一些信息到达时,它可以调用A。您可以在此处查看示例项目

One option is to switch from startService() to bindService() and use the local binding pattern. Then, you need to have A call a method on S at some point to register a listener or callback method. Then, S will have something it can call on A when some info arrives. You can see a sample project for that here.

或者,您可以留下 startService(),并使用广播 Intent 让S告诉A一些信息到达。您可以看到一个演示此类广播的示例项目 Intent 此处

Alternatively, you could leave startService() in place and use a broadcast Intent to let S tell A about some info arriving. You can see a sample project demonstrating such a broadcast Intent here.

这篇关于在Android中:如何调用服务的活动功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆