Android Jetpack compose WorkManager for background services

Android Jetpack compose WorkManager for background services. Android Jetpack is a great feature provided by the Android Team. I’ve outlined some of the amazing features of Jetpack including Navigation via NavigUI along with Pager Library to Jetpack.

Android Jetpack compose WorkManager for background services

you can read hare.

  • android workmanager background service example.
  • android-workmanager background service example github.
  • android workmanager periodic work request example.
  • android workmanager example.

What exactly is WorkManager?

WorkManager is among the components of Android Jetpack Articheture libraries that are utilized to run background services once the constraint is met. We all know that Google has now made it difficult the use background services such as Service or Intent Service to Doze Mode. If you are planning to use the background service then it must be run from the background.

When it comes to periodic or scheduled background services are constantly taking up resources such as AlarmManager which consumes large amounts of memory. In this scenario, WorkManager is the best developed for background service. WorKManager works with every version of API that is either one-time jobs required or periodic requirements to run the task.

What are the reasons for requiring WorkManager?

When you must execute the task that runs in the background, it means it doesn’t matter whether your application is running not. WorkManager offers the assurance of ensuring that your Job will run as planned within the System whether it’s a OneTime Job or Schedule Job when it is required. For instance, when you have to transfer remote server’s data as well as upload data to distant servers or get data frequently from local databases, this kind of job.

There are numerous benefits of working with the WorkManager.

  1. It is compatible with the latest version that uses the Android API.
  2. It is designed to provide background service on demands to finish the job.
  3. Perform the Job until the Constraint is satisfied.
  4. Most effective when you maintain your device’s condition.
  5. Perform the task either simultaneously or synchronously.
  6. You can easily make an easily-created Chaining of Jobs

How can I make use of the WorkManager?

Let’s build the app to get a better understanding of how to use the WorkManager. Let’s look at a basic example that, when a button is clicked by a user WorkManager runs its One Time job and sends an email confirming that the work has been completed. We can also observe the status of the Work Manager to check the status of the job.

Android Jetpack Compose Periodic WorkManager example.

in the below example, you can get full source code and steps for making a background server with workManager. Create a new android project with the jetpack activity and follow the below steps.


Step 1: Create an Android project with jetpack activity.

create activity in your project choose with jetpack activity and other simple kotlin class. You can use the below dependencies in your app base Gradle build file.

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation ''
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
    implementation 'androidx.activity:activity-compose:1.4.0'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

    // work manager
    implementation ""
    // required to avoid crash on Android 12 API 31
    implementation ''


Step 2: Open your Activity kotlin class and used below source code. 

In the below kotlin code, we make a simple screen with the toolbar and a button on the screen without using XML code.  using android jetpack composes.  And create a background service with workManager.

MainActivity Clase Source code.  

package com.codeplayon.WorkManger
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.*
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Observer
import com.codeplayon.WorkManger.ui.theme.PeriodicWorkManagerTheme
import java.util.concurrent.TimeUnit

class MainActivity : ComponentActivity() {
    private lateinit var worker: WorkManager

    override fun onCreate(savedInstanceState: Bundle?) {
        setContent {
            PeriodicWorkManagerTheme {
                Surface(color = MaterialTheme.colors.background) {
                    worker = WorkManager.getInstance()
                    val textInput = remember { mutableStateOf("") }
                    val powerConstraints = Constraints.Builder().setRequiresCharging(true).build()
                    val taskData = Data.Builder().putString(MESSAGE_STATUS, "Notification Done.").build()
                    val work = PeriodicWorkRequestBuilder<NotificationWorker>(1, TimeUnit.MINUTES)
                    worker.enqueueUniquePeriodicWork("Notify", ExistingPeriodicWorkPolicy.KEEP, work)

                    worker.getWorkInfoByIdLiveData(, Observer { workInfo ->
                        workInfo.let {
                            if (it.state.isFinished) {
                                val outputData = it.outputData
                                val taskResult = outputData.getString(NotificationWorker.WORK_RESULT)
                                if (taskResult != null) {
                                    textInput.value = taskResult
                            } else {
                                val workStatus = workInfo.state
                                textInput.value = workStatus.toString()

                      topBar =  {
                            title = {
                                    text = "Jetpack Periodic Work Manager",
                                    modifier = Modifier.fillMaxWidth(),
                                    textAlign = TextAlign.Center
                    ) {
                            modifier = Modifier.fillMaxSize(),
                            horizontalAlignment = Alignment.CenterHorizontally,
                            verticalArrangement = Arrangement.Center
                        ) {
                            Button(onClick = { worker.enqueue(work) }) {
                                Text(text = "Submit")
                            Spacer(modifier = Modifier.height(30.dp))
                            Text(text = textInput.value)

    companion object {
        const val MESSAGE_STATUS = "message_status"


When you copy the code you can see the error you can reply it your them class name and the method name

Step 3 Create a Notification Worker Class and used below source code.

import android.content.Context
import android.os.Build

class NotificationWorker(context: Context, workerParameters: WorkerParameters):
 Worker(context, workerParameters) {
    override fun doWork(): Result {
        val taskData = inputData
        val taskDataString = taskData.getString(MainActivity.MESSAGE_STATUS)

            "Make it Easy",

        val outputData = Data.Builder().putString(WORK_RESULT, "Task Finished").build()

        return Result.success(outputData)

    private fun showNotification(task: String, desc: String) {
        val manager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) 
as NotificationManager
        val channelId = "message_channel"
        val channelName = "message_name"

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(channelId, channelName, 

        val builder = NotificationCompat.Builder(applicationContext, channelId)


    companion object {
        const val WORK_RESULT = "work_result"

now you can build your project and run it to test your android jetpack Periodic WorkManager.


Read More :


You may also like...