问题描述
我有一个活动 (A) 和一个由 A 启动的服务 (S),如下所示:
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){...}
现在我想从 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:另一种方式(轮询 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()
并使用本地绑定模式.然后,您需要让 A 在某个时刻调用 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 中:如何从服务调用活动的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!