Android Question How can I stop a service from within itself?

I have a service running and I want to stop it. I have tried:
StopService(Me)
CancelScheduledService(Me)

neither of which actually stop the service.


The service is started by a forground activity with:
StartService(Service1Sec)

('Service1Sec' is the name of the service being started)
(The forground activity is then closed down after the starting the service)

The service uses:
StartServiceAt( Me, DateTime.Now + 1 * 1000, True)
within the Service_Start event to keep it restarting every second

I have tried: StopService(Me) and StopService("") within the Service_Start event to stop the service.

The service continues to restart every second whatever I do.

Can anyone see why the service won't stop?
 

JohnC

Expert
Licensed User
Longtime User
Try reversing the two statments to this order:

CancelScheduledService(Me)
StopService(Me)


Because the Stopservice line might be immediately killing the service on that line and never running the next line of "cancelscheduledservices", so the Last startserviceat time you set will still be executed and will bring it to life again.
 
Upvote 0
The correct answer is that you should remove the service. StartServiceAt no longer works and it never was an alternative to a timer.
So there is a new way to start a service?

I was not using a service as a timer. I was using a service to run code that I wanted to keep active even during sleep (checking the time) or when the forground activity was removed when other apps were started.

I just can't find how to stop the service when the event it checks for has been met.

I will search for up to date examples of service use if StartServiceAt is not a valid method.
 
Upvote 0
Top