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

我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。


当前回答

同样,如果使用pending intent(例如使用AlarmManager),人们可能会发现另一种替代方法更干净:

public static boolean isRunning(Class<? extends Service> serviceClass) {
    final Intent intent = new Intent(context, serviceClass);
    return (PendingIntent.getService(context, CODE, intent, PendingIntent.FLAG_NO_CREATE) != null);
}

CODE是一个常量,您在类中私有地定义它,以标识与您的服务相关联的挂起意图。

其他回答

如果服务属于另一个进程或APK,则使用基于ActivityManager的解决方案。

如果您可以访问它的源,只需使用基于静态字段的解决方案。但是我建议使用Date对象来代替布尔值。在服务运行时,只需将其值更新为'now',当它完成时将其设置为null。从活动中,您可以检查它是否为空或日期太旧,这将意味着它没有运行。

您还可以从您的服务发送广播通知,表明正在运行以及进一步的信息,如进度。

得到它!

你必须调用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;
     }
}

我只是想给@Snicolas的答案加上一个注释。以下步骤可以使用/不调用onDestroy()来检查停止服务。

onDestroy() called: Go to Settings -> Application -> Running Services ->选择并停止服务。 onDestroy()未调用:转到设置->应用程序->管理应用程序->选择并“强制停止”您的应用程序,其中您的服务正在运行。但是,由于您的应用程序在这里停止,因此服务实例也肯定会停止。

最后,我想提一下,在单例类中使用静态变量的方法对我来说是有效的。

检测服务是否正在运行的唯一有效/最快/干净的方法是创建PING/PONG功能。

在服务内部实现Messenger或AIDL方法:isAlive()——它返回服务的状态。

不要实现广播,因为它们可能被错过。

我稍微修改了上面给出的一个解决方案,但是传递的是类而不是泛型字符串名称,以便确保比较来自同一个方法class. getname()的字符串

public class ServiceTools {
    private static String LOG_TAG = ServiceTools.class.getName();

    public static boolean isServiceRunning(Context context,Class<?> serviceClass){
        final ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        for (RunningServiceInfo runningServiceInfo : services) {
            Log.d(Constants.TAG, String.format("Service:%s", runningServiceInfo.service.getClassName()));
            if (runningServiceInfo.service.getClassName().equals(serviceClass.getName())){
                return true;
            }
        }
        return false;
    }
}

然后

Boolean isServiceRunning = ServiceTools.isServiceRunning(
                    MainActivity.this.getApplicationContext(),
                    BackgroundIntentService.class);