What is WorkManager?
WorkManager is one of the Android Architecture Component and part of Android Jetpack. WorkManager is an Android library that runs deferrable background work when the work’s constraints are satisfied. WorkManager allows you to schedule work to run one- time or repeatedly using flexible scheduling windows.
How to use WorkManager?
Step 1:
In Build.gradle
Add the dependency of workmanager in your app build.gradle implementation “androidx.work:work-runtime:$work_version”
Step 2:
Create a Worker class
Create a Worker class public class BackgroundTask extends Worker { public static final String TAG = BackgroundTask.class.getName(); private static final String WORK_RESULT = "work_result"; private Context context; public BackgroundTask(@NonNull Context context, @NonNull WorkerParameters workerParams) { super(context, workerParams); } @NonNull @Override public Result doWork() { Log.d(TAG, "doWork()-->Task Begin"); Data data = getInputData(); String fileName = data.getString("fileName"); uploadImage(); return Result.success(); } }
Step 3:
Create a Work Request
- Create a work constraints object because constraints ensure that work is deferred until optimal conditions are met means work manager will work until when the specified condition will available.
Constraints constraints = new Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build();
- Schedule a one time task
WorkManager mWorkManager = WorkManager.getInstance(this); OneTimeWorkRequest uploadWork = new OneTimeWorkRequest.Builder(BackgroundTask.class) .setConstraints(constraints) .addTag("upload") .build(); mWorkManager.enqueueUniqueWork("UniqueWork", ExistingWorkPolicy.APPEND_OR_REPLACE, uploadWork);
- Schedule a periodic task
PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(BackgroundTask.class, 1, TimeUnit.HOURS, 1, TimeUnit.MINUTES) .setConstraints(constraints) .addTag(AppConstants.TAG_UPLOAD) .build(); mWorkManager.enqueueUniquePeriodicWork( "PeriodicTask", ExistingPeriodicWorkPolicy.KEEP, //Existing Periodic Work policy periodicWorkRequest //work request );
- If you want to pass the data
Data.Builder dataBuilder = new Data.Builder(); dataBuilder.putString(AppConstants.FOLDER_ID, folderId); Data data = dataBuilder.build(); OneTimeWorkRequest uploadWork = new OneTimeWorkRequest.Builder(BackgroundTask.class) .setConstraints(constraints) .setInputData(data) .addTag("upload") .build(); PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(BackgroundTask.class, 1, TimeUnit.HOURS, 1, TimeUnit.MINUTES) .setConstraints(constraints) .setInputData(data) .addTag(AppConstants.TAG_UPLOAD) .build();