What is WorkManager
WorkManager is a library used to enqueue deferrable, asynchronous tasks that is guaranteed to execute sometime after its Constraints are met.
WorkManager allows observation of work status and the ability to create complex chains of work.
This API allows you to schedule jobs (one-off or repeating) and chain.
WorkManager is a simple, but incredibly flexible library that has many additional benefits.
1.Support for both asynchronous one-off and periodic tasks
2.Support for constraints such as network conditions, storage space, and charging status
3.Chaining of complex work requests, including running work in parallel
4. Supports chained tasks with input/output, one work request used as input for the next
5. Handles API level compatibility back to API level 14.
6.Works with or without Google Play services
7.Follows system health best practices
8. Guarantees task execution, even if the app or device restart
When to use WorkManager
1. Periodically syncing local data with the network
2.A task initiated in response to an external event (FCM + WorkManager)
WorkManager classes
Worker: Worker have only one method to implement doWork() which is executed on a background thread. It’s the place where all your background tasks should be done
WorkRequest: This represents a request to do some work. You’ll pass in your Worker as part of creating your WorkRequest.
When making the WorkRequest you can also specify things like Constraints(e.g., internet, charging ) on when the Worker should run.
WorkManager: This class actually schedules your WorkRequest and makes it run.
WorkResult: Success, Failure, Retry.
Data: Persistable set of key/value pairs which are passed to/from Worker.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
//Add Input data Data requestData = new Data.Builder() .putInt(key_one, 42) .putBoolean(key_two, true) .putString(key_three, "23X@3") .build(); //Set Constraints Constraints constraints = new Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED).build(); //Create and enqueue a OneTimeWorkRequest that uses those arguments OneTimeWorkRequest myWorker = new OneTimeWorkRequest.Builder(MyWorker.class) .setConstraints(constraints) .setInputData(requestData) .build(); WorkManager.getInstance().enqueue(myWorker); //Observe work request status WorkManager.getInstance().getWorkInfoByIdLiveData(myWorker.getId()) .observe(lifecycleOwner, info -> { if (info != null && info.getState().isFinished()) { int result = info.getOutputData().getInt(KEY_RESULT, "default value"); } }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Define the Worker class public class MyWorker extends Worker { public MyWorker( @NonNull Context context, @NonNull WorkerParameters params) { super(context, params); } @Override public Result doWork() { //do the your work... //set the output Data output = new Data.Builder() .putInt(KEY_RESULT, result) .build(); return Result.success(output); } } |
References: