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”列。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…