在Android的:如何呼叫活动的功能从服务?功能、Android

2023-09-12 04:27:50 作者:无心少女毒如蝎

我有一个活动(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将有一些可以在通话时的一些信息到达。你可以看到一个示例项目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.