1. Definition and Importance

1.14. Service Lifecycle

Service Lifecycle

  1. onCreate(): Called when the service is first created.
  2. onStartCommand(): Called when a request is sent to the service.
  3. onBind(): Called when an activity binds to the service.
  4. onDestroy(): Called when the service is stopped.

Example Code

public class MyService extends Service {

    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {

        // Perform background work here

        return START_STICKY;

    }

 

    @Override

    public IBinder onBind(Intent intent) {

        return null;

    }

}

Use Cases

  • Playing music in the background.
  • Handling network requests.
  • Running scheduled tasks.