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 'com.google.android.material:material:1.5.0'
    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 "android.arch.work:work-runtime-ktx:1.0.1"
    // required to avoid crash on Android 12 API 31
    implementation 'androidx.work:work-runtime-ktx:2.7.0'
}

 

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.foundation.layout.*
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.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.Observer
import androidx.work.*
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?) {
        super.onCreate(savedInstanceState)
        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)
                        .setConstraints(powerConstraints)
                        .setInputData(taskData)
                        .build()
                    worker.enqueueUniquePeriodicWork("Notify", ExistingPeriodicWorkPolicy.KEEP, work)

                    worker.getWorkInfoByIdLiveData(work.id).observe(this, 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()
                            }
                        }
                    })

                    Scaffold(
                      topBar =  {
                          TopAppBar(
                            title = {
                                Text(
                                    text = "Jetpack Periodic Work Manager",
                                    modifier = Modifier.fillMaxWidth(),
                                    textAlign = TextAlign.Center
                                )
                            }
                          )
                      }
                    ) {
                        Column(
                            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.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.work.Data
import androidx.work.Worker
import androidx.work.WorkerParameters

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

        showNotification(
            "Make it Easy",
            taskDataString.toString()
        )

        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, 
NotificationManager.IMPORTANCE_DEFAULT)
            manager.createNotificationChannel(channel)
        }

        val builder = NotificationCompat.Builder(applicationContext, channelId)
            .setContentTitle(task)
            .setContentText(desc)
            .setSmallIcon(R.drawable.ic_outline_notifications_active_24)

        manager.notify(1, builder.build())
    }

    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...