如何重启服务?

How Do I Restart A Service?

我有一个服务,我想在用户点击特定按钮时停止,然后重新启动,我有:

    stopService(new Intent(getBaseContext(), TimerService.class));
    startService(new Intent(getBaseContext(), TimerService.class));

然而,我的印象是,每次我点击按钮时,这实际上是在创建多个服务。如何在不创建重复项的情况下启动和停止相同的服务?

编辑:不幸的是,建议的项目对我不起作用。不幸的是,在尝试实施给定的答案时,它并没有改变任何东西。我的初始计时器在滴答时记录下来,不幸的是滴答仍在发生,因为嵌套在 onFinish 函数中的第二个计时器仍未发生。所以一定不能停止服务。

我认为您的问题可能在于使用 getBaseContext()check out this answer. I've had issues using base context with services. Also, check your intent, you're creating a new intent on with the stop server instead of using the reference service to stop it. Check out this answer as well.

尝试:

    Intent i = new Intent(getApplicationContext(), TimerService.class);
    stopService(i);