15 Service
15 Service
Contents
● What is Service?
● Types of Services
● Service Lifecycle
● How to use Service
● Intent Service
What is Service?
A Service is an Android component that performs long-running tasks in
the background without a user interface. Key characteristics:
● Started via Intent: Initiated using startService() or bindService().
● Runs in Background: Continues running even if the user switches
apps.
● Main Thread: Executes on the app’s main thread (use worker threads
for heavy tasks).
● Lifecycle Management: Developers must manage its lifecycle.
● Inter-app Usage: Other apps can access it with proper permissions.
What is Service?
● Service is good for:
○ Network transactions.
○ Play music.
○ Perform file I/O.
○ Interact with a database.
Types of Services
● Started Service
○ Started with startService()
○ Runs indefinitely until it stops itself or called stopService() from outside
○ Usually does not update the UI
● Bound Service
○ Started with bindService().
○ Provides a client-server interface for components to interact with the
service.
○ Ends when all clients unbind.
Types of Services
● Foreground Service:
○ Runs in the background but displays a persistent notification to inform
the user (e.g., music player).
○ Higher priority, less likely to be killed by the system.
○ Mandatory notification cannot be dismissed while running.
Service Lifecycle
● The lifecycle methods manage a service’s creation, operation, and destruction:
● onCreate(): Called when the service is created (first startService() or bindService()).
● onStartCommand(): Called for started services with the starting Intent. Returns:
○ START_STICKY: Restarts with null Intent if killed.
○ START_NOT_STICKY: Does not restart if no pending Intents.
○ START_REDELIVER_INTENT: Restarts with the last Intent.
● onBind(): Returns a Binder object for bound service communication.
● onUnbind(): Called when all clients disconnect. Returns true to allow onRebind() for
new clients.
● onRebind(): Called when new clients bind after onUnbind().
● onDestroy(): Called when the service is no longer needed; clean up resources.
Background Service Limitations (API 26+)
● Background Apps: Cannot start background services.
● Foreground Apps: Can run both foreground and background services.
● System Behavior: Stops background services when the app moves to the background.
● startService(): Throws IllegalStateException in background apps targeting API 26+.
● Exemptions: Foreground and bound services are unaffected.
IntentService
● An IntentService is a subclass of Service for handling asynchronous requests: