1

我想在我的活动中显示我的服务的当前状态。我已经看到该服务可以与不同操作的活动绑定,但我只想知道它是启动还是停止。

我的主要活动启动和停止我的服务

startService(new Intent(MainActivity.this, MyService.class));
stopService(new Intent(MainActivity.this, MyService.class));

事实上,我的服务是“STICKY”并在后台做一些事情。我希望活动在文本视图中显示服务的状态(如“正在运行”或“未运行”,第二个组合将是启动/停止服务的按钮。(带有根据状态更改的标签(“启动服务”/“停止服务”)。

那么实现它的最佳技术解决方案是什么?

谢谢

4

2 回答 2

0

您可以使用ActivityManager.getRunningServices()

http://developer.android.com/reference/android/app/ActivityManager.html#getRunningServices%28int%29

于 2013-07-02T16:24:15.753 回答
0

我找到了这个。

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

然后,这意味着我需要在活动恢复时刷新标签(服务是否运行)和按钮(启动/停止服务)。并每 X 秒重现一次更新。我认为它可以工作。

我只是期待一些更“活”和实用的东西,但它确实有效。

于 2013-07-04T06:29:54.100 回答