Android Background Tasks Using WorkManager | Kotlin

Aziz
Huawei Developers
Published in
4 min readJan 12, 2024

--

Android

Introduction

Hello everyone! Since the release of Android, developers have experimented with various approaches for background tasks, such as AsyncTask, JobScheduler, among others. However, with Marshmallow and Oreo versions, the Android development team introduced restrictions on power optimization and background tasks.

Therefore, developers need to choose the best approach for background tasks. This is where WorkManager comes in, eliminating the need to deal with a variety of tools like Firebase Job Dispatcher, Alarm Manager + Broadcast Receivers, and Job Scheduler, making it easier to manage background tasks.

Android Devices

What is WorkManager?

WorkManager is part of the Android Jetpack library and provides a unified API for scheduling and managing background tasks. It intelligently manages tasks based on factors such as device status, battery status, network conditions, etc. WorkManager ensures that tasks are executed even if the application or device is restarted. It supports both one-time and periodic tasks and allows constraints and dependencies to be defined.

Key Features

  1. One-time and Periodic Tasks: WorkManager supports both one-time and periodic background tasks. In this way, it can be used in various scenarios within the application.
  2. Assured Execution: Guarantees tasks to complete even if the app or device is restarted. This feature is important to improve user experience.
  3. Network Connectivity and Charge Status Control: WorkManager provides restrictions to control whether tasks can be executed based on network status and the device’s charge status.
  4. Backwards Compatibility: It can be used on Android 4.0 (API level 14) and above, which appeals to a wide range of devices.
  5. Work Scheduling: WorkManager offers a flexible structure to schedule tasks based on a specific date or a specific time period.

Why Should We Use WorkManager?

  1. Easy to Use: WorkManager makes it easy to manage background tasks and provides developers with a cleaner and more streamlined API.
  2. Advanced Battery Optimization: Battery optimization has become increasingly important in current versions of Android. WorkManager schedules and manages tasks in a battery-friendly way.
  3. Accurate Schedules: WorkManager schedules tasks sensitively to factors such as device charging status and network status, which improves the application’s performance and battery life.
  4. Backwards Compatibility: WorkManager supports a wide range of Android versions, ensuring seamless operation on existing and new devices.

Using WorkManager

To create a background task using WorkManager, you must create a subclass of the ‘Worker’ class and implement the ‘doWork()’ method. This method should include work to be performed in the background.

class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) { 
override fun doWork(): Result { // Arka plandaki işlemler burada gerçekleştirilir
// İşlemler
return Result.success()
}
}

In the ‘doWork()’ method you can perform background tasks such as network requests, database operations or file operations. The ‘result’ value indicates the execution status of the task.

One-Time Task Planning

You can use the ‘OneTimeWorkRequest’ class to schedule a one-time background task with WorkManager. A simple example:

val workRequest = OneTimeWorkRequestBuilder<MyWorker>().build() 
WorkManager.getInstance(context).enqueue(workRequest)

In the above code, we create a job request by specifying the MyWorker class using ‘OneTimeWorkRequestBuilder’ and then queue the job request using the ‘enqueue()’ method.

Periodic Task Planning

WorkManager supports ‘PeriodicWorkRequest’ class for scheduling periodic tasks. You can use this example to define a background task that should be executed at regular intervals:

val workRequest = PeriodicWorkRequestBuilder<MyWorker>(1, TimeUnit.DAYS).build() 
WorkManager.getInstance(context).enqueue(workRequest)

In the code above, we create a ‘PeriodicWorkRequestBuilder’ by specifying the MyWorker class and the interval duration (1 day in this case). We then queue the job request using the ‘enqueue()’ method.

Restrictions and Dependencies

WorkManager allows you to set restrictions and dependencies for your background tasks. You can add constraints that specify conditions such as network availability, state of charge, and dependencies that specify relationships between tasks.

In the example below, you can see how to add constraints and dependencies to a task:

val constraints = Constraints.Builder() 
.setRequiredNetworkType(NetworkType.UNMETERED)
.setRequiresCharging(true)
.build()

val workRequest = OneTimeWorkRequestBuilder<MyWorker>()
.setConstraints(constraints)
.addTag("myTask")
.build()

val otherWorkRequest = OneTimeWorkRequestBuilder<OtherWorker>()
.addTag("otherTask")
.build()

WorkManager.getInstance(context)
.beginWith(workRequest)
.then(otherWorkRequest)
.enqueue()

In the code above, we specify the network type and state of charge requirements by creating a ‘Constraints’ object. Next, we set the constraints using the ‘setConstraints(constraints)’ method while creating the job request using ‘OneTimeWorkRequestBuilder’. You can also add tags to job requests and use ‘beginWith()’ and ‘then()’ to determine dependencies between tasks.

Android Devices

Conclusion

WorkManager is a powerful tool offered by Android Jetpack that makes it easy to manage background tasks in Android applications. It is designed to overcome the limitations of previous approaches and provide developers with a seamless user experience. WorkManager helps developers manage background tasks effectively by providing a unified API, intelligent task execution, and support for constraints and dependencies.

In this article, we explained the basics of WorkManager, examined why it is needed, showed how to schedule one-time and periodic tasks, add constraints and dependencies. WorkManager is an essential tool for developers who want to develop responsive and efficient Android applications.

References

--

--