Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

android - 如何检查服务是否在Android上运行?(How to check if a service is running on Android?)

How do I check if a background service is running?

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

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.

(我想要一个可切换服务状态的Android活动-它可以让我在关闭状态下将其打开,在开启状态下将其关闭。)

  ask by Bee translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I use the following from inside an activity:

(我在活动中使用以下内容:)

private boolean isMyServiceRunning(Class<?> serviceClass) {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

And I call it using:

(我称它为:)

isMyServiceRunning(MyService.class)

This works reliably, because it is based on the information about running services provided by the Android operating system through ActivityManager#getRunningServices .

(这是可靠的,因为它基于有关Android操作系统通过ActivityManager#getRunningServices提供的运行服务的信息。)

All the approaches using onDestroy or onSometing events or Binders or static variables will not work reliably because as a developer you never know, when Android decides to kill your process or which of the mentioned callbacks are called or not.

(所有使用onDestroy或onSometing事件或Binders或静态变量的方法都无法可靠地工作,因为作为开发人员,您永远不知道Android何时决定终止您的进程或是否调用了上述回调。)

Please note the "killable" column in the lifecycle events table in the Android documentation.

(请注意Android文档中生命周期事件表中的“ killable”列。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...