在Android的:如何呼叫活动的功能从服务? [英] In Android: How to Call Function of Activity from a Service?
问题描述
我有一个活动(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 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()
,并使用本地绑定模式。然后,你需要有一个叫S上的方法,在某些时候注册一个监听器或回调方法。然后,S将有一些可以在通话时的一些信息到达。你可以看到一个示例项目<一href="http://github.com/commonsguy/cw-andtutorials/tree/master/18-LocalService/Patchy/">here.
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()
到位,并使用广播意图
来设S说了什么一些信息到达。你可以看到一个示例项目演示这样的广播意图
的>。
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屋!