android - 在安卓 : How to Call Function of Activity from a Service?

标签 android service callback android-activity android-intent

我有一个 Activity (A) 和一个由 A 启动的服务 (S):

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

A 在 A 中有一个这样的函数:

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

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

PS:反过来(轮询 S 获取新信息)不是我所需要的。我找到了足够的信息来了解如何做到这一点。

最佳答案

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

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

关于android - 在安卓 : How to Call Function of Activity from a Service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2843874/

相关文章:

javascript - Angular 如何在我的情况下设置服务

active-directory - 在 Windows Server 2008 R2 中创建服务帐户

c++ - 面向对象的 C++ 抽象架构

ruby-on-rails - 在 Rails 中运行另一个方法之前调用一个方法

android - 在构造函数中设置 BitmapDrawable 资源

android - 包裹 : unable to marshal value

php - PHP 中的多级 JSON 数组

android - 如何在 Xamarin.Forms 中获取/检测屏幕大小?

templates - 撰写文件Docker中的模板语法

javascript - 如何将值传递给 AngularJS $http 然后回调