Build an Android background service with IntentService
Creating a background service with IntentService gives an Android app a simple way to process a queued Intent away from the UI thread. A database read, short network call, or file operation can run without freezing the Activity, and the service stops once the queue is empty.
IntentService is not a universal background-work solution. It was deprecated in Android API 30, and modern apps normally use WorkManager for jobs that may be deferred, retried, or constrained. It remains valuable for small operations and for understanding Android’s Service lifecycle.
This Kotlin example covers declaration, dispatch, result delivery, failure handling, and platform limits. It also considers Australian conditions such as prepaid data allowances, patchy reception on city routes, and different scheduling time zones.
Why IntentService still has a place
IntentService extends Service and manages a serial queue of requests. Each startService call reaches onStartCommand on the main thread, which places the Intent on an internal queue. Android then invokes onHandleIntent on a worker thread while the interface remains responsive.
That serial behaviour is useful when writes must not overlap, such as uploading a small batch of records in order. It also prevents several slow operations from creating an uncontrolled collection of threads. A large backlog still increases memory use and delays every later item.
Choose it only when the work has a short, predictable lifetime. WorkManager offers stronger scheduling controls and survives process death more gracefully. Developers seeking broader fundamentals can also explore hands-on development resources before choosing a modern alternative.
Prepare the Android project
Create an ordinary Android app and add an empty Service class named SyncService. No third-party library is required. Keep business logic separate from Activity code so it can be tested without a running screen.
Declare the class in AndroidManifest.xml. An exported service can be invoked by other apps, which is unnecessary for this internal request and increases the attack surface.
<service
android:name=".SyncService"
android:exported="false" />
Test on an emulator first, then on a physical handset with mobile data disabled. From Android 8.0, a background app cannot start a normal service. Call startService while your Activity is visible, or use WorkManager when the operation must begin after the user leaves the app. Calling startForegroundService also requires an immediate foreground notification, so it is not a drop-in replacement.
Handle work on the worker thread
onHandleIntent is the worker entry point. The Intent arrives with the data needed for the job, and this callback should perform one bounded unit of work. Returning normally tells IntentService that the queue item is complete.
Here, the service reads a destination label and simulates a short upload. The upload function represents a repository or API call; replace it with a cancellable operation and never sleep merely to imitate background work.
class SyncService : IntentService("SyncService") {
override fun onHandleIntent(intent: Intent?) {
val destination = intent?.getStringExtra(EXTRA_DESTINATION)
?: return
val uploaded = upload(destination)
sendResult(intent, uploaded)
}
companion object {
const val EXTRA_DESTINATION = "destination"
const val EXTRA_RECEIVER = "receiver"
const val RESULT_OK = 0
const val RESULT_ERROR = 1
}
}
Catch expected network errors around this call, report a failed result, and let the service stop. Do not update views directly because the worker has no safe view lifecycle. Store durable progress in Room or SQLite if the job must survive a restart, and give repeated operations an idempotency key so a retry cannot duplicate a purchase or upload.
Start the service and return results
Start the request from a visible Activity. Package needed data into the Intent, and pass a ResultReceiver when the Activity needs an immediate status update.
val receiver = object : ResultReceiver(Handler(Looper.getMainLooper())) {
override fun onReceiveResult(code: Int, data: Bundle?) {
status.text = data?.getString("message") ?: "No worries"
}
}
val request = Intent(this, SyncService::class.java)
.putExtra(SyncService.EXTRA_DESTINATION, "Sydney depot")
.putExtra(SyncService.EXTRA_RECEIVER, receiver)
startService(request)
The receiver is Parcelable and can travel in the Intent. Its callback is delivered on the main thread when given a main-thread Handler. Inside the service, retrieve the receiver and send the final status:
private fun sendResult(request: Intent, success: Boolean) {
val receiver: ResultReceiver? = if (Build.VERSION.SDK_INT >= 33) {
request.getParcelableExtra(EXTRA_RECEIVER, ResultReceiver::class.java)
} else {
@Suppress("DEPRECATION")
request.getParcelableExtra(EXTRA_RECEIVER)
}
receiver?.send(
if (success) RESULT_OK else RESULT_ERROR,
Bundle().apply {
putString("message", if (success) "Synced" else "Failed")
}
)
}
A callback does not survive process death, so persist the final state and let the Activity collect it on its next launch. If the job uses a user account, establish authentication before dispatching it; this Google Sign-In guide provides a practical setup and keeps credentials out of the Intent.
Apply practical patterns for Australian use
Australian mobile conditions reward restraint. A phone can lose signal while moving through a Sydney rail tunnel or along a Melbourne tram route, while many prepaid plans include a limited monthly data allowance. A failed upload may therefore be temporary rather than a server fault.
Time-based jobs also need care because Sydney, Melbourne, Adelaide, and Perth use different time zones, and daylight-saving rules vary. Use an IANA zone such as Australia/Sydney rather than a fixed UTC offset. Friendly wording can use local language sparingly; “No worries” suits a status message, while server logs and formal notices should stay clear.
Before dispatching
Keep the payload small by sending an ID instead of a large bitmap or dataset. Prefer WorkManager when the job needs a network or charging constraint. Make the operation idempotent and record a stable job ID.
Inside the worker
Catch timeouts and I/O errors, then send a clear failure code. Check isStopped between units and publish lightweight progress. Avoid retry storms when a prepaid data cap is close. Store results locally so the Activity can recover them.
Those habits make the service dependable without keeping a permanent notification or consuming background data. If the operation must continue for many minutes and the user expects visible progress, use a foreground service with the correct declared type and notification. If it can wait, move it to WorkManager.
Compare Android background work options
The right comparison depends on runtime guarantees rather than simply which API is older. IntentService suits a brief operation that can finish promptly; WorkManager suits durable deferred work; JobScheduler fits platform-controlled schedules; a foreground service suits user-visible work that continues immediately.
| Option | Best suited to | Key benefit | Main limitation |
|---|---|---|---|
| IntentService | One immediate, short task | Simple serial worker | Deprecated from API 30; must finish promptly |
| WorkManager | Deferred or constrained work | Retries, persistence, and constraints | Not intended for real-time execution |
| JobScheduler | Platform-controlled schedules | Battery-aware system scheduling | Less flexible than WorkManager |
| Foreground service | Work the user must see | Immediate, continuous execution | Notification, permissions, and declared type |
For a new app, choose WorkManager unless the task is demonstrably immediate and brief. IntentService still teaches the queue-and-thread pattern behind many older Android examples, and using it with bounded work, explicit errors, and modern start restrictions can produce a small, dependable implementation.