skip to content

In an Android Service, what do START_STICKY, START_NOT_STICKY and START_REDELIVER_INTENT returned from onStartCommand change when the process is killed?

level: middleimportance: must knowfreq 60%

answer

  1. what happens after a kill
  2. restart with or without the Intent
  3. a null Intent on a sticky restart
  4. stopSelf(startId) ends redelivery
  5. the default return is START_STICKY

basics

~20 s

If the process dies after onStartCommand returns, START_STICKY recreates the service with a null Intent, START_NOT_STICKY leaves it stopped until the next explicit start, and START_REDELIVER_INTENT recreates it and redelivers the last Intent until stopSelf(startId).

solid answer

~40 s

The return value tells the system what to do with the service's started state if its process is killed after `onStartCommand()` returns. `START_STICKY` keeps it started and recreates it, calling `onStartCommand()` with a `null` Intent when nothing is pending, which suits long-running work started and stopped explicitly. `START_NOT_STICKY` drops it unless new starts are pending, which suits work something else will trigger again. `START_REDELIVER_INTENT` recreates it and redelivers the last Intent, with `START_FLAG_REDELIVERY` in `flags`, until the service calls `stopSelf(startId)`, which suits a one-shot command that must finish. In Kotlin, declare the parameter as `Intent?`, stop with the `startId` so newer requests are not lost, and move the work off the main thread, where `onStartCommand()` runs. The default implementation returns `START_STICKY`.

code

kotlin · 21 lines
kotlin
class ClipExportService : Service() {
    private val executor = Executors.newSingleThreadExecutor()

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val clipId = intent?.getStringExtra(EXTRA_CLIP_ID)
        if (clipId == null) {
            stopSelf(startId)
            return START_NOT_STICKY
        }
        if ((flags and START_FLAG_REDELIVERY) != 0) {
            Log.i(TAG, "Export of $clipId redelivered after a kill")
        }
        executor.execute {
            exportClip(clipId) // idempotent: may run twice
            stopSelf(startId)  // ends redelivery for this start
        }
        return START_REDELIVER_INTENT
    }

    override fun onBind(intent: Intent): IBinder? = null
}

go deeper

for a junior

Recall the three constants and that they only matter if the process is killed after onStartCommand() returns.

for a middle

Explain the null Intent on a sticky restart, redelivery until stopSelf(startId), the START_FLAG_REDELIVERY bit, and the START_STICKY default.

for a senior

Pick a mode per command in a real app, make redelivered work idempotent, and stop with start IDs in order so no request is lost.

for a principal

Treat restart semantics as part of a component's contract: decide which work may be dropped, which must finish, and which belongs in a scheduled job instead of a service.

## What the return value controls Every call to `startService()` or `startForegroundService()` reaches the service as `onStartCommand(intent, flags, startId)`, on the app's main thread. The `Int` the method returns is not a status code: it tells the system what to do with the service's **started state** if the app's process is killed after `onStartCommand()` has returned. Low memory is the classic cause; the system can reclaim a background process at any time. The three values an app normally returns are constants on `Service`: | Return value | After the process is killed | Intent on restart | |---|---|---| | `START_STICKY` | Stays started; the system recreates the service later | `null` if no start requests are pending | | `START_NOT_STICKY` | Taken out of the started state unless new starts are pending; not recreated until the next explicit start | never `null` | | `START_REDELIVER_INTENT` | Recreated, and the last delivered `Intent` is delivered again | the redelivered `Intent` | A fourth constant, `START_STICKY_COMPATIBILITY`, is the legacy variant of sticky that does not guarantee `onStartCommand()` is called again; modern code does not return it. The default implementation of `onStartCommand()` returns `START_STICKY` for apps targeting any current SDK. ## Reading each mode - **`START_STICKY`** suits work that is started and stopped explicitly and runs for an arbitrary time, such as background playback. The system recreates the service and calls `onStartCommand()` again; if no start commands are pending, the `Intent` is `null`, so the service must rebuild its state from storage rather than from extras. - **`START_NOT_STICKY`** suits work that can simply be dropped and will be triggered again by something else, the documentation's example being a poll that an alarm restarts every N minutes. The service will never see a `null` Intent because it is not restarted without a pending one. - **`START_REDELIVER_INTENT`** suits one-shot commands that must finish, such as exporting a specific clip. The `Intent` stays scheduled for redelivery until the service calls `stopSelf(startId)` with that start's ID, and a redelivered start carries the `START_FLAG_REDELIVERY` bit in `flags`. Because the work may run twice, it should be idempotent. ## Writing onStartCommand so a restart cannot crash it 1. **Declare the Intent nullable in Kotlin.** `onStartCommand` overrides a Java method, so Kotlin lets you write `intent: Intent`, but a sticky restart passes `null` and the generated parameter null check then crashes the service. Write `intent: Intent?`. 2. **Use the startId.** Each request has a unique `startId`. `stopSelf(startId)` or `stopSelfResult(startId)` stops the service only if that is the most recent start, so a request that arrived while you were finishing an older one is not lost. A bare `stopSelf()` stops regardless. 3. **Stop in order.** The Javadoc warns that stopping with the newest ID before older ones stops the service anyway, so when work is spread across threads, finish and stop in the order received; a single-thread executor gives you that order for free. 4. **Leave the main thread.** `onStartCommand()` runs where the UI runs; hand the work to a worker thread and return quickly. ## Choosing a mode in a dash-cam app - The **recording service** is started by the user and stopped by the user. A restart after a kill cannot resume the lost camera session, so `START_NOT_STICKY`, letting the user restart, is a reasonable choice; returning `START_STICKY` means writing restart logic that copes with a `null` Intent. - The **clip export command** names one clip in its extras and must finish, so `START_REDELIVER_INTENT` with `stopSelf(startId)` after each export is the natural fit. - A **periodic check** that something else will trigger again needs no restart: `START_NOT_STICKY`. ## Foreground services and restarts The return mode interacts with the background rules that newer Android versions added: - Since Android 12 (API 31), apps targeting API 31 or higher may not start a foreground service from the background, but the `Service` Javadoc states that this restriction does not affect the system's **restarts** of a sticky foreground service. Starting a sticky service from the background is still restricted. - A foreground service of type `shortService` does not support sticky behaviour at all. - The return value never protects a service from being killed. What lowers that risk is being bound to an activity that has user focus or, far more, running in the foreground.

  • Why pass the startId to stopSelf() instead of calling stopSelf() with no argument?
    `stopSelf(startId)` and `stopSelfResult(startId)` stop the service only if that ID is the most recent start, so a request that arrived while you finished an older one keeps the service alive. A bare `stopSelf()` stops it regardless, and with `START_REDELIVER_INTENT` the start ID is also what ends redelivery of that Intent.
  • Does the Android 12 background-start rule stop a sticky foreground service from being restarted?
    No. The `Service` Javadoc says the rule that blocks apps targeting API 31 or higher from starting foreground services in the background does not affect the system's restarts of a sticky foreground service; starting one from the background yourself is still restricted. A `shortService` foreground service cannot be sticky at all.

  • START_STICKY redelivers the original Intent after a restart.
  • START_NOT_STICKY means the system will never kill the service.
  • With START_STICKY the Intent parameter can safely be non-null in Kotlin.
  • START_REDELIVER_INTENT keeps redelivering even after stopSelf(startId) for that start.
  • The return value is a success code the system logs for the start request.