Sobes.tech
Middle

What is the lifecycle of services in Android?

sobes.tech AI

Answer from AI

The service has no UI and runs in the background. Its lifecycle is managed by three main methods:

  • onCreate(): Called the first time the service is created. Initialization is performed here.
  • onStartCommand() / method called when binding (e.g., onBind()): onStartCommand() is called when the service is started with startService(). It returns a flag indicating how the system should restart the service if it is killed. onBind() is called when a client binds to the service with bindService().
  • onDestroy(): Called when the service is destroyed. All resources are released here.

There are two types of services affecting the lifecycle:

  • Started Service: Started with startService(). Runs until explicitly stopped with stopSelf() or stopService(). The system will attempt to restart it after destruction if onStartCommand() returned the appropriate flag.
  • Bound Service: Started with bindService(). Exists as long as at least one active client is bound to it. When all clients unbind, the service is destroyed. onBind() returns an IBinder implementation used for interaction with the service.

Lifecycle diagram:

        Start Service --+--> onStartCommand() --+--> Running
                        |                         |
        Bind Service ---+--> onBind() -----------+--> Bound
                        |
        onCreate() -----+
                        |
                        +--> onRebind()
                        |
        onDestroy() <---+-------------------------+---- Unbound <--- unbindService()
                                                 |
                                                 +---- Stopped <--- stopSelf() / stopService()

Key points:

  • onCreate() is called only once.
  • onStartCommand() can be called multiple times if startService() is called repeatedly.
  • Service runs on the main UI thread by default. Long-running operations should be performed in a separate thread or using IntentService.
  • Bound services have a more complex lifecycle depending on client state.

Example onStartCommand():

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // Perform some actions
    // For example, start background work
    
    // Return a flag indicating the system's behavior upon service destruction
    return START_STICKY; // Service will be recreated if killed
}

Example onBind():

private final IBinder binder = new LocalBinder();

public class LocalBinder extends Binder {
    MyService getService() {
        // Return the service instance for clients
        return MyService.this;
    }
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return binder;
}

@Override
public boolean onUnbind(Intent intent) {
    // Called when all clients unbind
    return super.onUnbind(intent);
}