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

Arc*_*pgc 5 service android

我正在运行服务以在我的应用程序中每1小时获取一次通知.

服务肯定每1小时运行一次; 我使用Logcat检查了它.

但是由于我在onResume()MainActivity中启动此服务,我想检查服务是否已经运行,并且只有在它没有运行时启动它.

我用过这段代码:

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;
}
Run Code Online (Sandbox Code Playgroud)

但我总是假的.

所以我查看了输出结果service.service.getClassName().我的服务不在列表中.

是因为我的申请未知吗?或者是其他东西?

Nak*_*kul 0

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

您是否已使用 开始您的服务context.startService()
确保清单文件包含以下内容:

<service android:name="com.android.MyApp.MyServices.NotificationsService" />
Run Code Online (Sandbox Code Playgroud)