Services
A Service is an Android component that performs long-running operations in the background or exposes functionality to other components, without a user interface.
Use a Service when:
Work must continue even if the app is not visible
Multiple components need to access the same background logic
The operation doesn’t belong to UI lifecycle
Service Lifecycle
onCreate()Called once
Initialize resources
Equivalent to setup phase
onStartCommand(Intent, flags, startId)Called when
startService()is invokedThis is where work usually begins
Can be called multiple times
onBind(Intent)Used for bound services
Returns an
IBinderIf unused, return
null
onDestroy()Cleanup
Types of Services
1. Started Service
Started using:
Characteristics:
Runs indefinitely until stopped
Independent of the component that started it
Must stop itself or be stopped explicitly
Stopping:
Typical use:
File download
Syncing data
Logging
Uploading analytics
2. Bound Service
Started using:
Characteristics:
Client-server model
Exists only while at least one client is bound
Exposes methods via
IBinder
Typical use:
Music playback control
Shared computation
Data providers within app
Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.
3. Started + Bound Service
Started → controls lifetime
Bound → controls communication
Service dies only when:
stopSelf()is called andall clients are unbound
Execution Modes of Services
Foreground Service:
A foreground service performs some operation that is noticeable to the user.
Foreground services must display a Notification.
Foreground services continue running even when the user isn't interacting with the app. (It stays alive even when the app is closed).
Example:
Music
Navigation
Ongoing call
Fitness tracking
Background Service:
A service running without foreground notification.
A background service performs an operation that isn't directly noticed by the user.
It runs only when the app is running, (It is terminated when the app is terminated).
Intent Service
Automatically runs on a single background thread
Processes intents sequentially (queue, since it's a single thread)
Stops itself when done
Why deprecated:
Poor flexibility
Replaced by better tools
MainActivity.java
MyIntentService.java