Android Service 多实例

标签 android service instance

我对 Android 服务类还是有点陌生​​。我知道您需要使用 startService(intent) 从您的应用程序启动服务,但我的问题是我的服务中有方法。我需要以 Intent 启动服务,然后在我的 Activity 中创建该类的对象,以便我可以调用服务的方法。问题是当我这样做时,当我以 Intent 启动服务时创建一个服务实例,当我在我的 Activity 中创建类的对象时创建另一个服务实例。这意味着当我创建服务对象时,从 startService(intent) 传递给服务的任何数据都不存在。解决这个问题的任何方法还是我只是完全滥用服务类?我可以提供一些代码,但基本上是这样的:

//Create Object of ControlPanel service class.
ControlPanel cPanel = new ControlPanel();
//Create intent for starting ControlPanel service class
Intent controlPanel = new Intent(this, cPanel.getClass());
//Start Service
startService(controlPanel);

最佳答案

我会说你在滥用类 :-)。

多次调用 startService() 不会导致启动多个服务。

来自doc :

Request that a given application service be started. The Intent can either contain the complete class name of a specific service implementation to start, or an abstract definition through the action and other fields of the kind of service to start. If this service is not already running, it will be instantiated and started (creating a process for it if needed); if it is running then it remains running.

你应该覆盖 onStartCommand()以及。如果服务尚未启动,则第一个 startService 调用会启动该服务。在任何情况下,onStartCommand 都会拦截任何进一步的 startService 调用以及您要发送给它的 Intent 。

关于Android Service 多实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15931462/

相关文章:

android - 不同 API 级别的不同 AndroidManifest 文件

java - 为什么我的服务在 Android 中不起作用? (我只想每 5 秒记录一次)

unix - 从 C/C++ 应用程序启动 systemd 服务或调用 D-Bus 服务

android - 当重新创建其布局包含 View 的 Activity 时,是否恢复了 View 的 "tag"?

android - setCompoundDrawablesWithIntrinsicBounds(int,int,int,int)不起作用

android - OBJ vs 3DS - Android 3D 开发的最佳格式是什么

Java:使用 GSON 序列化 RSA 公钥

php - 在这个例子中如何正确返回类值? PHP

c++ - 定义生成元素 vector 的函数时正确的方法是什么 C++

Android AnimationDrawable返回空指针异常