In this article, we’ll look at what the WorkManager API in Android is and how to use WorkManager. What is WorkManager, how does it work, and what are the benefits? So let’s get started.
Output:
Contents
What is WorkManager?
WorkManager is an Android Jetpack library that makes it simple to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or the device restarts. For example, if your app restarts due to an issue, Work Manager ensures that the scheduled task runs again.
WorkManager is an Android Jetpack component. WorkManager assists us in completing our tasks as soon as possible or at the appropriate time.
WorkManager is a task scheduler that makes it simple to specify asynchronous tasks and when they should be completed. The Work Manager API assists in the creation of the task and passing it to the Work Manager for execution immediately or at the specified time. For example, you might tell your app to periodically download new resources from the network now that downloading is a task, you can schedule it to run at a specific time based on the WIFI network’s availability or when the device is charging. As a result, you can use WorkManager to schedule a task in this manner.
Need of WorkManager
The Android development team has been working on battery optimizations since Marshmallow. Following that, the team introduced the Doze mode. Then, in Oreo, a variety of restrictions were placed on performing background jobs. Prior to WorkManager, we used various job schedulers, such as Firebase JobDispatcher, Job Scheduler, and Alarm Manager + Broadcast receivers, to perform background tasks. As a result, it’s difficult for developers to decide which scheduler to use and which is the best. As a result, the Work Manager is in charge of such matters. We must give the task to the WorkManager, who will use the Firebase Job Dispatcher, Alarm Manager + Broadcast Receivers, and Job Scheduler to perform the background task depending on the requirement.
Benefits of Using WorkManager
- It has backward compatibility, which means you don’t have to figure out what the device can do or which API to use. All you have to do now is hand the task over to the WorkManager. It will select the most appropriate method for completing the task.
- It provides guaranteed and constraint-aware execution. In other words, depending on the situation, you can schedule a task when it will work. WorkManager takes care of all the restrictions and ensures that the task is performed, even when the device is reboot and the app is out of operation without running the task.
- WorkManager supports tasks query, you can not just schedule the task, but you can also check if the task is running or if the task has stopped or if it was successful or failed. So the task status can be detected.
- It supports the task chain, which means that the work manager allows you to draw up a draught of your work one after the other.
WorkManager Example
The sample project below demonstrates how to use workManager, register it for a specific event, and use it in the application.
Step 1: Create a New Project in Android Studio.
Step 2: Add the workManager dependency in build.gradle(Module:app).
implementation 'androidx.work:work-runtime-ktx:2.6.0'
Step 3: Working with the MainActivity.kt file, add the code given below.
package com.sagar.workmanager import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.work.* import java.util.concurrent.TimeUnit class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) MyWorkManager() } private fun MyWorkManager() { val constraints = Constraints.Builder() .setRequiresCharging(false) .setRequiredNetworkType(NetworkType.NOT_REQUIRED) .setRequiresBatteryNotLow(true) .build() val myRequest = PeriodicWorkRequest.Builder(MyWorker::class.java, 15, TimeUnit.MINUTES) .setConstraints(constraints).build() WorkManager.getInstance(this) .enqueueUniquePeriodicWork( "MY_SELF", ExistingPeriodicWorkPolicy.KEEP, myRequest ) } }
Step 4: Create a new class, name it MyWorker and add the code given below.
package com.sagar.workmanager import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.work.Worker import androidx.work.WorkerParameters class MyWorker(context: Context, workerParameters: WorkerParameters) : Worker(context, workerParameters) { companion object { const val CHANNEL_ID = "channel_id" const val NOTIFICATION_ID = 1 } override fun doWork(): Result { Log.d("Main", "WorkManager- Complete") showNotification() return Result.success() } private fun showNotification() { val intent = Intent(applicationContext, MainActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent = PendingIntent.getActivity(applicationContext, 0, intent, 0) val notification = NotificationCompat.Builder( applicationContext, CHANNEL_ID ) .setSmallIcon(R.drawable.ic_baseline_work_24) .setContentTitle("DevelopersDome") .setContentText("Android development Tutorials") .setPriority(NotificationCompat.PRIORITY_MAX) .setAutoCancel(true) .setContentIntent(pendingIntent) if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){ val channelName = "Channel Name" val channelDescription = " Channel Description" val channelImportance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel(CHANNEL_ID,channelName,channelImportance).apply { description = channelDescription } val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } with(NotificationManagerCompat.from(applicationContext)){ notify(NOTIFICATION_ID,notification.build()) } } }
Step 5: In activity_main.xml file add the code given below.
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Developers Dome" android:textSize="30sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHorizontal_bias="0.568" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Run the application now. You will get the output shown in the output section, after every 15 Minutes the workManager repeat.
Source Code:
We’ve completed the development of the WorkManager in Android application. You can get the Source code from the given below button.
- We hope that this guide will assist you in understanding all about the concepts of Broadcast Receiver in Android. We have concentrated on making a basic, meaningful and easy-to -learn guide to the concepts of Broadcast Receiver with suitable examples. Still if you have any problems regarding this, please post them in the comments section, we will be glad to assist you.
You might also like:
Using Hilt Dependency Injection in Android App | Notes App