On Android, how does a started Service differ from a bound one, and how does an activity reach its app's service through a local Binder?
answer
- two ways in: start or bind
- onStartCommand versus onBind
- who decides when it stops
- onServiceConnected delivers the IBinder
- no disconnect callback on unbind
basics
~20 sA started Service runs from startService() until stopSelf() or stopService(); a bound Service lives while clients hold a bindService() connection. In one process, onBind() returns a Binder subclass whose getService() method hands the client the service instance.
solid answer
~40 sA **started** service is launched with `startService()` or `startForegroundService()`, receives each request in `onStartCommand()` on the main thread, and runs until it calls `stopSelf()` or someone calls `stopService()`. A **bound** service is reached with `bindService()`: the system calls `onBind()` for the first client, caches that `IBinder` for later ones, and destroys the service when the last client unbinds, unless it was also started. For a service private to your app and process, extend `Binder` with a method like `getService()`, return it from `onBind()`, and cast the `IBinder` in `ServiceConnection.onServiceConnected()`. Bind in `onStart()` with `BIND_AUTO_CREATE`, call `unbindService()` in `onStop()`, and clear the reference yourself: `onServiceDisconnected()` fires only when the connection is lost unexpectedly, never on unbind.
code
kotlin · 35 linesclass RecorderService : Service() {
private val binder = LocalBinder()
var isRecording = false
private set
inner class LocalBinder : Binder() {
fun getService(): RecorderService = this@RecorderService
}
override fun onBind(intent: Intent): IBinder = binder
}
class RecorderActivity : ComponentActivity() {
private var recorder: RecorderService? = null
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
recorder = (service as RecorderService.LocalBinder).getService()
}
override fun onServiceDisconnected(name: ComponentName) {
recorder = null // process died; not called on unbind
}
}
override fun onStart() {
super.onStart()
bindService(Intent(this, RecorderService::class.java), connection, Context.BIND_AUTO_CREATE)
}
override fun onStop() {
super.onStop()
unbindService(connection)
recorder = null
}
}go deeper
Know the two entry calls, startService() and bindService(), which callback each triggers, and who ends each kind of service.
Explain the local Binder pattern end to end, why onBind() runs once per service, and why onServiceDisconnected() is not an unbind signal.
Show you pair bind and unbind with onStart() and onStop(), keep work off the main thread, and know when a started-and-bound service outlives its clients.
Weigh when an in-process bound service earns its place at all versus a plain object held by the app, and when crossing processes justifies the IPC cost.
## Two ways a component reaches a Service An Android **`Service`** is an application component that runs without a screen. Other components reach it in one of two ways, and the way they reach it decides how long it lives. - A **started service** is launched with `startService()` or `startForegroundService()`. The system calls `onCreate()` once, then `onStartCommand()` for every start request, and the service keeps running until it calls `stopSelf()` or another component calls `stopService()`. - A **bound service** is reached with `bindService()`. The system calls `onBind()`, which returns an `IBinder`, the programming interface clients call. The service lives only while at least one client is bound; after the last client unbinds, the system destroys it. - A service can be **both**. If it was started, unbinding every client does not destroy it: it still needs `stopSelf()` or `stopService()`. | | Started | Bound | |---|---|---| | Entry call | `startService()` / `startForegroundService()` | `bindService()` | | Service callback | `onStartCommand()` per request | `onBind()` for the first client | | Ends when | `stopSelf()` or `stopService()` | the last client unbinds (unless also started) | | Gives the caller | nothing back | an `IBinder` through `ServiceConnection` | Both callbacks run on the app's **main thread**. A service is not a thread: `onStartCommand()` that does network or disk work directly blocks the UI of every activity in the process, so the work goes to a worker thread. ## The bound path step by step Binding is asynchronous. `bindService(intent, connection, flags)` returns a boolean straight away, not the binder. The `ServiceConnection` you pass receives the binder later: 1. The client calls `bindService()` with an **explicit** `Intent` naming the service class and usually the flag `Context.BIND_AUTO_CREATE`, which creates the service if it is not running. Since Android 5.0 (API 21) an implicit intent here throws. 2. The system calls the service's `onBind()` for the first client only, then caches that `IBinder` and hands the same object to every later client without calling `onBind()` again. 3. The system calls `onServiceConnected(name, service)` on the client with that `IBinder`. 4. When the client is done it calls `unbindService(connection)`. `onServiceDisconnected()` is easy to misread: the system calls it only when the connection is **lost unexpectedly**, for example when the service's process crashes or is killed. It is **not** called when the client unbinds, so a client clears its own reference after `unbindService()`. ## The local Binder When the service is private to your app and runs in the **same process** as its clients, which is the common case, the Android documentation prefers extending `Binder`: - Declare an inner class, for example `LocalBinder : Binder()`, with a method such as `getService()` that returns the service instance (or another object the service hosts). - Return one instance of it from `onBind()`. - In `onServiceConnected()`, cast the `IBinder` to `LocalBinder` and call `getService()`; from then on the client calls the service's public methods directly. Nothing is marshalled: these are ordinary method calls on the calling thread. That is also the limit of the technique. If the service runs in another process (an `android:process` attribute) or another app binds to it, the cast fails and you need a `Messenger` or an AIDL interface, which belong to the lesson on cross-process communication. ## Where to bind and unbind Pair the calls with the client's lifecycle: - Bind in `onStart()` and unbind in `onStop()` when the activity needs the service only while visible. - Bind in `onCreate()` and unbind in `onDestroy()` only when it must talk to the service even while stopped. - Do not bind and unbind in `onResume()` and `onPause()`; those run on every transition and churn the connection. - Call `unbindService()` even when `bindService()` returned `false`; the documentation warns that otherwise the client keeps the service from shutting down when idle. - A `BroadcastReceiver` cannot bind to a service at all; only activities, services and content providers can. ## A dash-cam example A dash-cam app's recording screen binds to its own `RecorderService` to show whether a recording is running and to toggle it. The service is started when the user starts a drive so that it outlives the screen; the screen binds in `onStart()` to read state through `LocalBinder.getService()` and unbinds in `onStop()`. Because the service was started, the user leaving the screen does not end the recording; the service ends itself with `stopSelf()` when the drive stops. Making that started recording survive in the background is the job of a foreground service, which is a separate topic.
- An activity starts a service with startService(), binds to it, then unbinds. Is the service destroyed?No. A service that was started stays alive after its last client unbinds; it ends only when it calls `stopSelf()` or a component calls `stopService()`. If `onUnbind()` returns `true`, the system calls `onRebind()` when a client binds again instead of `onBind()`.
- When does a local Binder stop being an option?When the client is in another process or another app. A local Binder relies on casting the `IBinder` to your own class and on plain in-process method calls; across processes the object is a proxy, so the cast fails and you need a `Messenger` or an AIDL interface instead.
- Why can't a BroadcastReceiver bind to your service?The bound-services guide says only activities, services and content providers can bind. A receiver lives only for its `onReceive()` call, so it cannot hold a connection; it starts work another way, such as starting a service within the background rules or scheduling a job.
A started service is a contractor hired for a job: it keeps working until it reports done or is let go. A bound service is an open phone line: it exists while someone is on the call and hangs up after the last caller leaves, unless the contractor was also hired.
- onServiceDisconnected() is called when the activity calls unbindService().
- bindService() returns the IBinder directly to the caller.
- A Service runs on its own background thread, so onStartCommand can do network calls.
- A local Binder works across processes as long as both belong to the same app.
- A service that was only bound keeps running after its last client unbinds.