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:

  1. We first need a 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) {
        }
      }
    }
  2. Then, we can start it as follows:
    StartService(new Intent(this, typeof(XamarinService)))
  3. Now, we can stop it in a very similar manner using the StopService() method on the Context type:
    StopService(new Intent(this, typeof(XamarinService)));
  4. We can also stop the service from inside the service using the StopSelf() method:
    StopSelf();
  5. If we use either the 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();
    }

How it works...

As a service is not tied to the lifecycle of activities or other app components, we have to start and stop them manually.

Tip

It is important that services are stopped in order to free up memory and other resources.

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.

See also

  • The Starting services recipe
  • The Handling simultaneous service requests recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.77.71