Architecture of Mobile Applications
1. Definition and Importance
1.14. Service Lifecycle
Service Lifecycle
- onCreate(): Called when the service is first created.
- onStartCommand(): Called when a request is sent to the service.
- onBind(): Called when an activity binds to the service.
- 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.