[英]In Android: How to Call Function of Activity from a Service?
I have an Activity (A) and a Service (S) which gets started by A like this: 我有一个活动(A)和一个服务(S),它由A启动,如下所示:
Intent i = new Intent();
i.putExtra("updateInterval", 10);
i.setClassName("com.blah", "com.blah.S");
startService(i);
A have a function like this one in A: A在A中有这样的功能:
public void someInfoArrived(Info i){...}
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! 现在我想从S.内部调用A.someInfoArrived(i).Inntnt.putExtra没有我可以传递Object引用等的版本...请帮忙!
PS: The other way around (A polling S for new info) is NOT what I need. PS:另一种方式(新信息的轮询S)不是我需要的。 I found enough info about how to do that.
我找到了关于如何做到这一点的足够信息。
One option is to switch from startService()
to bindService()
and use the local binding pattern. 一种选择是从
startService()
切换到bindService()
并使用本地绑定模式。 Then, you need to have A call a method on S at some point to register a listener or callback method. 然后,您需要在某个时刻在S上调用一个方法来注册一个监听器或回调方法。 Then, S will have something it can call on A when some info arrives.
然后,当某些信息到达时,S将会在A上调用它。 You can see a sample project for that here .
您可以在此处查看示例项目。
Alternatively, you could leave startService()
in place and use a broadcast Intent
to let S tell A about some info arriving. 或者,您可以保留
startService()
并使用广播Intent
让S告诉A有关某些信息到达。 You can see a sample project demonstrating such a broadcast Intent
here . 您可以在此处查看演示此类广播
Intent
的示例项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.