Services

    Quickview

    • A service can run in the background to perform work
    • A service can allow other components to bind to it, in order to interact with it and perform interprocess communication
    • A service runs in the main thread of the application that hosts it, by default

    In this document

    1. The Basics
      1. Declaring a service in the manifest
    2. Creating a Started Service
      1. Extending the Service class
      2. Starting a service
      3. Stopping a service
    3. Creating a Bound Service
    4. Managing the Lifecycle of a Service
      1. Implementing the lifecycle callbacks

    Key classes

    1. Service

    See also

    1. Bound Services

A Service is an application component that can perform operations in the background. Another application component can start a service and it will continue to run in the background even if the user switches to another application. Additionally, a component can bind to a service to interact with it and even perform interprocess communication (IPC). For example, a service might handle network transactions, or perform file I/O, all from the background.

A service can essentially take two forms:

Started
A service is "started" when an application component (such as another service) starts it by calling startService(). Once started, a service can run in the background indefinitely, even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.
Bound
A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.

Although this documentation generally discusses these two types of services separately, your service can work both ways—it can be started (to run indefinitely) and also allow binding. It's simply a matter of whether you implement a couple callback methods: onStartCommand() to allow components to start it and onBind() to allow binding.

Regardless of whether your application is started, bound, or both, any application component can use the service (even from a separate application), in the same way that any component can use a service—by starting it with startService().

Caution: A service runs in the main thread of its hosting lightweight process—the service does not create its own thread and does not run in a separate lightweight process. This means that, if your service is going to do any CPU intensive work or blocking operations (such as long-running computations or networking), you should create a new thread within the service to do that work.

The Basics

To create a service, you must create a subclass of Service (or one of its existing subclasses). In your implementation, you need to override some callback methods that handle key aspects of the service lifecycle and provide a mechanism for components to bind to the service, if appropriate. The most important callback methods you should override are:

onStartCommand()
The system calls this method when another component, such as a service, requests that the service be started, by calling startService(). Once this method executes, the service is started and can run in the background indefinitely. If you implement this, it is your responsibility to stop the service when its work is done, by calling stopSelf() or stopService(). (If you only want to provide binding, you don't need to implement this method.)
onBind()
The system calls this method when another component wants to bind with the service (such as to perform RPC), by calling bindService(). In your implementation of this method, you must provide an interface that clients use to communicate with the service, by returning an IBinder. You must always implement this method, but if you don't want to allow binding, then you should return null.
onCreate()
The system calls this method when the service is first created, to perform one-time setup procedures (before it calls either onStartCommand() or onBind()). If the service is already running, this method is not called.
onDestroy()
The system calls this method when the service is no longer used and is being destroyed. Your service should implement this to clean up any resources such as threads, registered listeners, receivers, etc. This is the last call the service receives.

If a component starts the service by calling startService() (which results in a call to onStartCommand()), then the service remains running until it stops itself with stopSelf() or another component stops it by calling stopService().

If a component calls bindService() to create the service (and onStartCommand() is not called), then the service runs only as long as the component is bound to it. Once the service is unbound from all clients, the system destroys it.

In the following sections, you'll see how you can create each type of service and how to use it from other application components.

Declaring a service in the manifest

To declare your service, add a <service> element as a child of the <application> element. For example:

<manifest ... >
  ...
  <application ... >
      <service mindroid:name=".ExampleService" />
      ...
  </application>
</manifest>

There are other attributes you can include in the <service> element to define other properties. The mindroid:name attribute is the only required attribute—it specifies the class name of the service. Once you publish your application, you should not change this name, because if you do, you might break some functionality where explicit intents are used to reference your service.

See the <service> element reference for more information about declaring your service in the manifest.

Creating a Started Service

A started service is one that another component starts by calling startService(), resulting in a call to the service's onStartCommand() method.

When a service is started, it has a lifecycle that's independent of the component that started it and the service can run in the background indefinitely, even if the component that started it is destroyed. As such, the service should stop itself when its job is done by calling stopSelf(), or another component can stop it by calling stopService().

An application component such as an service can start the service by calling startService() and passing an Intent that specifies the service and includes any data for the service to use. The service receives this Intent in the onStartCommand() method.

For instance, suppose an service needs to save some data to an online database. The service can start a companion service and deliver it the data to save by passing an intent to startService(). The service receives the intent in onStartCommand(), connects to the Internet and performs the database transaction. When the transaction is done, the service stops itself and it is destroyed.

Caution: A services runs in the same process as the application in which it is declared and in the main thread of that application, by default. So, if your service performs intensive or blocking operations, the service will slow down the overall performance. To avoid impacting application performance, you should start a new thread inside the service.

Extending the Service class

The following example code is an implementation of the Service class. The example code starts a worker thread for each start request to perform the job and processes only one request at a time.

package hello;

public class HelloService extends Service {
  private Looper mServiceLooper;
  private ServiceHandler mServiceHandler;

  // Handler that receives messages from the thread
  private final class ServiceHandler extends Handler {
      public ServiceHandler(Looper looper) {
          super(looper);
      }
     
      public void handleMessage(Message msg) {
          // Normally we would do some work here, like download a file.
          // For our sample, we just sleep for 5 seconds.
          long endTime = System.currentTimeMillis() + 5*1000;
          while (System.currentTimeMillis() < endTime) {
              synchronized (this) {
                  try {
                      wait(endTime - System.currentTimeMillis());
                  } catch (Exception e) {
                  }
              }
          }
          // Stop the service using the startId, so that we don't stop
          // the service in the middle of handling another job
          stopSelf(msg.arg1);
      }
  }

  public void onCreate() {
    // Start up the thread running the service.  Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block.  We also make it
    // background priority so CPU-intensive work will not disrupt our UI.
    HandlerThread thread = new HandlerThread();
    thread.start();
    
    // Get the HandlerThread's Looper and use it for our Handler 
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
  }

  public int onStartCommand(Intent intent, int flags, int startId) {
      // For each start request, send a message to start a job and deliver the
      // start ID so we know which request we're stopping when we finish the job
      Message msg = mServiceHandler.obtainMessage();
      msg.arg1 = startId;
      mServiceHandler.sendMessage(msg);
      return 0;
  }

  public IBinder onBind(Intent intent) {
      // We don't provide binding, so return null
      return null;
  }
  
  public void onDestroy() {
  }
}

Starting a Service

You can start a service from another service or other application component by passing an Intent (specifying the service to start) to startService(). The Mindroid system calls the service's onStartCommand() method and passes it the Intent. (You should never call onStartCommand() directly.)

For example, a service can start the example service in the previous section (HelloSevice) using an explicit intent with startService():

Intent intent = new Intent();
intent.setClassName("hello", "HelloService");
startService(intent);

The startService() method returns immediately and the Mindroid system calls the service's onStartCommand() method. If the service is not already running, the system first calls onCreate(), then calls onStartCommand().

If the service does not also provide binding, the intent delivered with startService() is the only mode of communication between the application component and the service.

Multiple requests to start the service result in multiple corresponding calls to the service's onStartCommand(). However, only one request to stop the service (with stopSelf() or stopService()) is required to stop it.

Stopping a service

A started service must manage its own lifecycle. So, the service must stop itself by calling stopSelf() or another component can stop it by calling stopService().

Once requested to stop with stopSelf() or stopService(), the system destroys the service as soon as possible.

However, if your service handles multiple requests to onStartCommand() concurrently, then you shouldn't stop the service when you're done processing a start request, because you might have since received a new start request (stopping at the end of the first request would terminate the second one). To avoid this problem, you can use stopSelf(int) to ensure that your request to stop the service is always based on the most recent start request. That is, when you call stopSelf(int), you pass the ID of the start request (the startId delivered to onStartCommand()) to which your stop request corresponds. Then if the service received a new start request before you were able to call stopSelf(int), then the ID will not match and the service will not stop.

Caution: It's important that your application stops its services when it's done working, to avoid wasting system resources. If necessary, other components can stop the service by calling stopService(). Even if you enable binding for the service, you must always stop the service yourself if it ever received a call to onStartCommand().

For more information about the lifecycle of a service, see the section below about Managing the Lifecycle of a Service.

Creating a Bound Service

A bound service is one that allows application components to bind to it by calling bindService() in order to create a long-standing connection (and generally does not allow components to start it by calling startService()).

You should create a bound service when you want to interact with the service from other services and other components in your application or to expose some of your application's functionality to other applications, through interprocess communication (IPC).

To create a bound service, you must implement the onBind() callback method to return an IBinder that defines the interface for communication with the service. Other application components can then call bindService() to retrieve the interface and begin calling methods on the service. The service lives only to serve the application component that is bound to it, so when there are no components bound to the service, the system destroys it (you do not need to stop a bound service in the way you must when the service is started through onStartCommand()).

To create a bound service, the first thing you must do is define the interface that specifies how a client can communicate with the service. This interface between the service and a client must be an implementation of IBinder and is what your service must return from the onBind() callback method. Once the client receives the IBinder, it can begin interacting with the service through that interface.

Multiple clients can bind to the service at once. When a client is done interacting with the service, it calls unbindService() to unbind. Once there are no clients bound to the service, the system destroys the service.

There are multiple ways to implement a bound service and the implementation is more complicated than a started service, so the bound service discussion appears in a separate document about Bound Services.

Managing the Lifecycle of a Service

The service lifecycle—from when it's created to when it's destroyed—can follow two different paths:

  • A started service

    The service is created when another component calls startService(). The service then runs indefinitely and must stop itself by calling stopSelf(). Another component can also stop the service by calling stopService(). When the service is stopped, the system destroys it..

  • A bound service

    The service is created when another component (a client) calls bindService(). The client then communicates with the service through an IBinder interface. The client can close the connection by calling unbindService(). Multiple clients can bind to the same service and when all of them unbind, the system destroys the service. (The service does not need to stop itself.)

These two paths are not entirely separate. That is, you can bind to a service that was already started with startService(). For example, a background download service could be started by calling startService() with an Bundle that identifies the file to download. Later, possibly when the user wants to exercise some download status over the file or get other information about the file, a service can bind to the download service by calling bindService(). In cases like this, stopService() or stopSelf() does not actually stop the service until all clients unbind.

Implementing the lifecycle callbacks

Like an activity, a service has lifecycle callback methods that you can implement to monitor changes in the service's state and perform work at the appropriate times. The following skeleton service demonstrates each of the lifecycle methods:

public class ExampleService extends Service {
    int mStartMode;       // indicates how to behave if the service is killed
    IBinder mBinder;      // interface for clients that bind
    boolean mAllowRebind; // indicates whether onRebind should be used

    public void onCreate() {
        // The service is being created
    }
    
    public int onStartCommand(Intent intent, int flags, int startId) {
        // The service is starting, due to a call to startService()
        return 0;
    }
    
    public IBinder onBind(Intent intent) {
        // A client is binding to the service with bindService()
        return mBinder;
    }
    
    public boolean onUnbind(Intent intent) {
        // All clients have unbound with unbindService()
        return true;
    }
    
    public void onDestroy() {
        // The service is no longer used and is being destroyed
    }
}

Note:You are not required to call the superclass implementation of these callback methods.

Figure 1. The service lifecycle. The diagram on the left shows the lifecycle when the service is created with startService() and the diagram on the right shows the lifecycle when the service is created with bindService().

By implementing these methods, you can monitor two nested loops of the service's lifecycle:

Note: Although a started service is stopped by a call to either stopSelf() or stopService(), there is not a respective callback for the service (there's no onStop() callback). So, unless the service is bound to a client, the system destroys it when the service is stopped—onDestroy() is the only callback received.

Figure 1 illustrates the typical callback methods for a service. Although the figure separates services that are created by startService() from those created by bindService(), keep in mind that any service, no matter how it's started, can potentially allow clients to bind to it. So, a service that was initially started with onStartCommand() (by a client calling startService()) can still receive a call to onBind() (when a client calls bindService()).

For more information about creating a service that provides binding, see the Bound Services document.