如何查看后台服务是否正在运行?
我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。
如何查看后台服务是否正在运行?
我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。
当前回答
你可以使用这个(我还没有尝试过,但我希望它能工作):
if(startService(someIntent) != null) {
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
}
如果已经有一个正在运行的服务,startService方法将返回ComponentName对象。如果不是,则返回null。
参见公共抽象ComponentName startService (Intent服务)。
这和检查不一样,因为它正在启动服务,所以你可以添加stopService(someIntent);按照规定。
其他回答
如果服务属于另一个进程或APK,则使用基于ActivityManager的解决方案。
如果您可以访问它的源,只需使用基于静态字段的解决方案。但是我建议使用Date对象来代替布尔值。在服务运行时,只需将其值更新为'now',当它完成时将其设置为null。从活动中,您可以检查它是否为空或日期太旧,这将意味着它没有运行。
您还可以从您的服务发送广播通知,表明正在运行以及进一步的信息,如进度。
Xamarin c#版本:
private bool isMyServiceRunning(System.Type cls)
{
ActivityManager manager = (ActivityManager)GetSystemService(Context.ActivityService);
foreach (var service in manager.GetRunningServices(int.MaxValue)) {
if (service.Service.ClassName.Equals(Java.Lang.Class.FromType(cls).CanonicalName)) {
return true;
}
}
return false;
}
我从一个活动内部使用以下:
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;
}
我称之为使用:
isMyServiceRunning(MyService.class)
这是可靠的工作,因为它是基于Android操作系统通过activitymanager# getRunningServices提供的运行服务的信息。
所有使用onDestroy或onSometing事件或binder或静态变量的方法都不会可靠地工作,因为作为开发人员,你永远不知道Android何时决定杀死你的进程,或者调用哪些提到的回调。请注意Android文档中生命周期事件表中的“killable”列。
首先,您不应该通过使用ActivityManager来访问服务。(下面讨论)
Services can run on their own, be bound to an Activity or both. The way to check in an Activity if your Service is running or not is by making an interface (that extends Binder) where you declare methods that both, the Activity and the Service, understand. You can do this by making your own Interface where you declare for example "isServiceRunning()". You can then bind your Activity to your Service, run the method isServiceRunning(), the Service will check for itself if it is running or not and returns a boolean to your Activity.
您还可以使用此方法停止您的服务或以其他方式与之交互。
这是我提出的一个很好的解决方案,但它只适用于运行在单独进程中的服务。这可以通过在manifest中添加一个android:process属性来实现。
<service
android:name=".ExampleService"
android:process="com.example.service"
...
现在,您的服务将运行在具有给定名称的单独进程中。从你的应用程序你可以打电话
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
activityManager.runningAppProcesses.any { it.processName == "com.example.service" }
如果服务正在运行,则返回true,否则返回false。
重要提示:请注意,它将显示您的服务是何时启动的,但当您禁用它时(即在系统从它解除绑定后),该进程仍然是活跃的。所以你可以简单地强制移除它:
override fun onUnbind(intent: Intent?): Boolean {
stopSelf()
return super.onUnbind(intent)
}
override fun onDestroy() {
super.onDestroy()
killProcess(Process.myPid())
}
然后它就完美地工作了。