0

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.

pls
  • 27
  • 5
  • is there handlers in the services or threads ? if yes you should stop them by overriding method onDestroy , example for handlers you should call handler.removecallbacksandmessages(null) and thus all handlers will be removed if you don't remove or destroy them they will remain active. if this is not ur case please share the service implementation – Badran Aug 22 '18 at 14:12
  • `startService` do not create another instance of service if it is already running, however if you want to do complete restart, consider destroying/releasing any resources/timers etc in your onDestroy and call `stopService` followed by `startService` – Qasim Aug 22 '18 at 14:13
  • 1
    Smart thinking Qasim. Will try. – pls Aug 22 '18 at 14:16

1 Answers1

0

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);
Petro
  • 3,484
  • 3
  • 32
  • 59