如何检查服务是否在 Android 上运行? [英] How to check if a service is running on Android?

查看:31
本文介绍了如何检查服务是否在 Android 上运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查后台服务是否正在运行?

How do I check if a background service is running?

我想要一个可以切换服务状态的 Android Activity——它让我在它关闭时打开它,如果它打开它让我关闭它.

I want an Android activity that toggles the state of the service -- it lets me turn it on if it is off and off if it is on.

推荐答案

不久前我也遇到了同样的问题.由于我的服务是本地的,我最终只是使用服务类中的静态字段来切换状态,如 hackbod 这里

I had the same problem not long ago. Since my service was local, I ended up simply using a static field in the service class to toggle state, as described by hackbod here

编辑(记录):

这里是hackbod提出的解决方案:

Here is the solution proposed by hackbod:

如果您的客户端和服务器代码是同一个 .apk 的一部分,并且您是使用具体的 Intent(一个指定了确切的服务类),那么您可以简单地将您的服务设置为客户端可以检查运行时的全局变量.

If your client and server code is part of the same .apk and you are binding to the service with a concrete Intent (one that specifies the exact service class), then you can simply have your service set a global variable when it is running that your client can check.

我们故意没有API来检查服务是否跑步是因为,当你想做某事时,几乎没有失败就像那样,您最终会在代码中遇到竞争条件.

We deliberately don't have an API to check whether a service is running because, nearly without fail, when you want to do something like that you end up with race conditions in your code.

这篇关于如何检查服务是否在 Android 上运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆