How to Integrate Work Manager in Android?

Anil Kr Mourya
4 min readJun 30, 2023

--

WorkManager is an Android library introduced by Google as part of the Android Jetpack architecture components. It provides a simple and flexible way to schedule and execute background tasks that need to run under various conditions, such as when the device is idle, charging, or connected to a network. WorkManager handles various complexities of managing background tasks, including task persistence, retries, and compatibility with different versions of Android.

To integrate WorkManager into your Android project, follow these steps:

1- Add the WorkManager dependency to your app’s build.gradle file:

dependencies {
// Other dependencies...
implementation "androidx.work:work-runtime:2.7.0"
}

2- Define a worker class that extends the Worker class provided by WorkManager. This class represents the background task you want to perform. Override the doWork() method, which contains the code to be executed in the background. For example:

public class MyWorker extends Worker {
public MyWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {
// Perform your background task here
// Return Result.SUCCESS if the task is completed successfully

// Example: Log a message
Log.d("MyWorker", "Background task executed");

return Result.success();
}
}

3- Schedule the background task using WorkManager. Typically, this is done in an appropriate place in your app, such as an Activity or a Fragment. For example:

// Create a OneTimeWorkRequest for your worker class
OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).build();

// Enqueue the work request with WorkManager
WorkManager.getInstance(context).enqueue(workRequest);

You can also customize the work request by setting additional constraints, specifying delays, defining periodic tasks, or chaining multiple tasks together. WorkManager provides various classes like Constraints, PeriodicWorkRequest, and WorkContinuation to achieve these functionalities.

4- Handle the result of the background task. You can add an addObserver() method to the work request to observe its status. For example:

WorkManager.getInstance(context)
.getWorkInfoByIdLiveData(workRequest.getId())
.observe(this, workInfo -> {
if (workInfo != null && workInfo.getState() == WorkInfo.State.SUCCEEDED) {
// Handle the successful completion of the background task
}
});

By observing the work request’s status, you can update the UI or take further action based on the result.

Benefits of using WorkManager:

  1. Background Task Management: WorkManager handles background tasks, ensuring they are executed even if the app is killed or the device restarts.
  2. Compatibility: WorkManager is compatible with Android API level 14 and higher, ensuring a consistent experience across a wide range of devices.
  3. Task Constraints: You can specify constraints for your background tasks, such as requiring a network connection or running only when the device is idle or charging.
  4. Flexibility: WorkManager offers various types of work requests, including one-time tasks and periodic tasks. You can also chain multiple tasks together for more complex workflows.
  5. Work Observability: WorkManager provides LiveData to observe the status of your background tasks, allowing you to update the UI or handle task results accordingly.
  6. Task Persistence: WorkManager automatically persists the tasks, which means that even if the app is closed or the device restarts, the pending tasks will be rescheduled and executed.

Example

Define a worker class that extends the Worker class provided by WorkManager:

import static com.nic.workmanagerexamplejava.MainActivity.TASK_KEY;

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;
// extand workmanager class Worker
public class MyWork extends Worker {
public static final String RECIVE_TASK_KEY="recive_massage";
public MyWork( @androidx.annotation.NonNull Context context, @androidx.annotation.NonNull WorkerParameters workerParams) {
super(context, workerParams);
}


@androidx.annotation.NonNull
@Override
public Result doWork() {
// get Input tasks by the User or work manager

Data data=getInputData();
// notification function
Notifactionshow("mr.appbuilder",data.getString(TASK_KEY));
// set a response when the Task is done
Data data1=new Data.Builder().putString(RECIVE_TASK_KEY,"mr.appbuilder Recive data Successfully and Thank you ").build();
// return the task status
return Result.success(data1);
}
// create notification method
public void Notifactionshow(String title,String desc){
NotificationManager notificationManager=(NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("mr.appbuilder", "mr.appbuilder", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}

NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "mr.appbuilder")
.setContentTitle(title)
.setContentText(desc)
.setSmallIcon(R.mipmap.ic_launcher);

notificationManager.notify(1, builder.build());

}
}

Create an activity and Schedule the background task using WorkManager:

import static com.nic.workmanagerexamplejava.MyWork.RECIVE_TASK_KEY;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.lifecycle.Observer;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {
public static final String TASK_KEY = "Input_TASK_KEY";
AppCompatTextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);

// Create input data for the worker
Data data = new Data.Builder()
.putString(TASK_KEY, "mr.appbuilder this massage send by data!")
.build();

// Define constraints for the worker like when the device is idle, charging, or connected to a network
Constraints constraints = new Constraints.Builder()
.setRequiresCharging(true)
.build();

//Create a one-time work request with input data and constraints
OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(MyWork.class)
.setInputData(data)
.setConstraints(constraints)
.build();

// Set a click listener to enqueue the work request when the button is clicked
findViewById(R.id.notifactionsend).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WorkManager.getInstance().enqueue(oneTimeWorkRequest);
}
});

// Observe the status of the work request
WorkManager.getInstance().getWorkInfoByIdLiveData(oneTimeWorkRequest.getId())
.observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(WorkInfo workInfo) {
try {
if (workInfo.getState().isFinished()) {
// Task has finished, display the output data
textView.append(workInfo.getOutputData().getString(RECIVE_TASK_KEY));
} else {
// Task is still running, display the current state
String status = workInfo.getState().name();
textView.append(status + "\n");
}
} catch (NullPointerException e) {
Log.e("TAG", "onChanged: " + e.getLocalizedMessage());
}
}
});
}
}

Conclusion

WorkManager is a powerful Android library provided by Google as part of the Android Jetpack architecture components. It offers an easy and flexible way to schedule and execute background tasks in Android applications. By integrating WorkManager into your project, you can ensure that your background tasks are executed efficiently, taking into account various device conditions and constraints, such as battery status, network connectivity, and device idle mode.

Project on github

Thank you

Anil Kr Mourya

--

--