Interview QuestionPractical QuestionFollow-up Questions

Managing Long Running Background Tasks on Android

skydovesJaewoong Eum (skydoves)||7 min read

Managing Long Running Background Tasks on Android

Android provides several mechanisms to handle long running background tasks while ensuring optimal resource usage and compliance with modern OS restrictions. The appropriate method depends on the nature of the task, its urgency, and its interaction with the app's lifecycle. By the end of this lesson, you will be able to:

  • Explain when to use WorkManager, Services, Coroutines, and JobScheduler.
  • Describe how WorkManager guarantees task execution under constraints.
  • Identify why Foreground Services require a persistent notification.
  • Compare lifecycle bound coroutine scopes with persistent task mechanisms.
  • Choose the correct tool based on task persistence, urgency, and lifecycle requirements.

WorkManager for Persistent Tasks

For tasks that need to run even if the app is closed or after a device reboot, WorkManager is the recommended solution. It manages background work and ensures tasks are executed under constraints like network availability or charging status:

class UploadWorker(
    appContext: Context,
    workerParams: WorkerParameters
) : Worker(appContext, workerParams) {
    override fun doWork(): Result {
        uploadData()
        return Result.success()
    }
}

val workRequest = OneTimeWorkRequestBuilder<UploadWorker>()
    .setConstraints(
        Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build()
    )
    .build()

WorkManager.getInstance(context).enqueue(workRequest)

WorkManager persists tasks in an internal database, so they survive app termination and device reboots. It supports one time and periodic work, chaining multiple tasks, and observing work status through LiveData or Flow.

Services for Continuous Tasks

For tasks that require continuous execution, like playing music or tracking location, Services run independently of the UI. A Foreground Service must display a persistent notification so the user is aware that the app is performing work in the background:

class MyForegroundService : Service() {
    override fun onStartCommand(
        intent: Intent?, flags: Int, startId: Int
    ): Int {
        startForeground(NOTIFICATION_ID, createNotification())
        performLongRunningTask()
        return START_NOT_STICKY
    }

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

This interview continues for subscribers

Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.

Become a Sponsor