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.
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:
Service
instance, such as an IntentService
instance:[Service] public class XamarinService : IntentService { private bool stopping = false; protected override void OnHandleIntent(Intent intent) { // some long-running task while (!stopping) { } } }
StartService(new Intent(this, typeof(XamarinService)))
StopService()
method on the Context
type:StopService(new Intent(this, typeof(XamarinService)));
StopSelf()
method:StopSelf();
StopService
or StopSelf
instance, the OnDestroy()
method is invoked on the service, which we use to clean up the service and stop any running tasks:public override void OnDestroy() { stopping = true; base.OnDestroy(); }
As a service is not tied to the lifecycle of activities or other app components, we have to start and stop them manually.
Services can be stopped in two ways, from within the service itself using the StopSelf()
method or from an external component using the StopService()
method on a Context
instance. Some service types, such as the IntentService
instance, will automatically stop themselves when they no longer have any task to perform. Services which inherit from the base Service
type do not automatically stop, and we have to stop them manually.
If the service handles the simultaneous execution of requests, we need to ensure that we do not stop the service if there are other requests running. When we handle requests in this instance, we are provided a start ID, which we can use to keep track of the service that is running. This ID is a sequential number representing the order in which the requests came in.