Search code examples
javaandroidandroid-service

How Do I Restart A Service?


I have a service that I want to be stopped and then started fresh whenever a user hits a specific button, to which I have:

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

However, I am under the impression that this is actually creating several services every time I hit the button. How do I start and stop the same service without creating duplicates?

EDIT: The items suggested unfortunately do not work for me. Upon attempting to implement the given answer it unfortunately does not change anything. My initial timer logs when its ticking and unfortunately the ticking is still occuring as the second timer, which is nested into the onFinish function is still yet to occur. So the services must not be stopped.


Solution

  • I believe your issue may lie within using 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.

    Try:

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