Android:检查我的服务是否在后台运行

5

我在我的应用程序中运行一个服务,每小时获取一次通知。

这个服务确实每小时运行一次;我使用Logcat检查了它。

但是由于我在MainActivity的onResume()中启动了这个服务,所以我想要检查服务是否已经在运行,只有在它没有运行时才启动它。

我使用了这段代码:

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("com.android.MyApp.MyServices.NotificationsService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

但是我总是得到 false

所以我检查了一下 service.service.getClassName() 的输出。我的服务没有在列表中。

这是因为我的应用程序未知吗?还是其他原因?


2
为什么需要检查服务是否正在运行?假设您使用context.startService(...)启动服务,只有在当前未运行服务时才会创建服务,但是您的服务的onStartCommand(...)始终会被调用。 - Ian Warwick
你的服务是否在“设置>应用程序>正在运行的服务”中列出? - Behzad Momahed Heravi
2个回答

0

我知道有点晚了,但这个答案可能会帮助其他正在寻找同样问题的人。

您是否使用context.startService()启动了服务?
请确保清单文件包含以下内容:

<service android:name="com.android.MyApp.MyServices.NotificationsService" />

0
private boolean isMyServiceRunning(Context mContext) {
    ActivityManager manager = (ActivityManager) mContext
            .getSystemService(Context.ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager
            .getRunningServices(Integer.MAX_VALUE)) {
        if (**HERE_YOUR_SERVICE'S_CLASS_NAME**.class.getName().equals(
                service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

// 我有后台GPS服务,并且我已经成功地检查了我的GPS服务是否在运行。

// 祝编码愉快...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接