Stopping services
As with most tasks, sometimes we have to stop doing them. This may be because it is no longer necessary or because there are problems.
How to do it...
In order to stop a Service
instance, an instance needs to be executing a task, otherwise the command will be ignored. Stopping a service can be done using a reference to the Context
instance or from within the service:
We first need a
Service
instance, such as anIntentService
instance:[Service] public class XamarinService : IntentService { private bool stopping = false; protected override void OnHandleIntent(Intent intent) { // some long-running task while (!stopping) { } } }
Then, we can start it as follows:
StartService(new Intent(this, typeof(XamarinService)))
Now, we can stop it in a very similar manner using the
StopService()
method on theContext
type:StopService(new Intent(this, typeof(XamarinService)));
We can also stop the service from inside the service using the
StopSelf()
method:StopSelf();
If we use...