如何查看后台服务是否正在运行?
我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。
如何查看后台服务是否正在运行?
我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。
当前回答
我从一个活动内部使用以下:
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”列。
其他回答
我只是想给@Snicolas的答案加上一个注释。以下步骤可以使用/不调用onDestroy()来检查停止服务。
onDestroy() called: Go to Settings -> Application -> Running Services ->选择并停止服务。 onDestroy()未调用:转到设置->应用程序->管理应用程序->选择并“强制停止”您的应用程序,其中您的服务正在运行。但是,由于您的应用程序在这里停止,因此服务实例也肯定会停止。
最后,我想提一下,在单例类中使用静态变量的方法对我来说是有效的。
你可以使用Android开发者选项中的这个选项来查看你的服务是否仍然在后台运行。
1. Open Settings in your Android device.
2. Find Developer Options.
3. Find Running Services option.
4. Find your app icon.
5. You will then see all the service that belongs to your app running in the background.
这更适用于Intent Service调试,因为它们会生成一个线程,但也适用于常规服务。我找到这个线程感谢宾
在我的例子中,我摆弄了调试器并找到了线程视图。它看起来有点像微软Word里的项目符号图标。无论如何,您不必在调试器模式下使用它。单击该流程并单击该按钮。任何Intent服务都会在运行时显示出来,至少在模拟器上是这样。
/**
* Check if the service is Running
* @param serviceClass the class of the Service
*
* @return true if the service is running otherwise false
*/
public boolean checkServiceRunning(Class<?> serviceClass){
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
{
if (serviceClass.getName().equals(service.service.getClassName()))
{
return true;
}
}
return false;
}
得到它!
你必须调用startService()为你的服务正确注册和传递BIND_AUTO_CREATE是不够的。
Intent bindIntent = new Intent(this,ServiceTask.class);
startService(bindIntent);
bindService(bindIntent,mConnection,0);
现在是ServiceTools类:
public class ServiceTools {
private static String LOG_TAG = ServiceTools.class.getName();
public static boolean isServiceRunning(String serviceClassName){
final ActivityManager activityManager = (ActivityManager)Application.getContext().getSystemService(Context.ACTIVITY_SERVICE);
final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);
for (RunningServiceInfo runningServiceInfo : services) {
if (runningServiceInfo.service.getClassName().equals(serviceClassName)){
return true;
}
}
return false;
}
}