Work Manager

If you want to perform any asychronus task at the background in case of app exit or system restart we can go for work manager instead of service and other since its not compaitable more then android 8 on app exit state.

Its support backward compatability then other schedulers.

And chaining of request is also possible in work manager.

It return result for the work either failure or success.

Major Component on Work Manager

worker class where we write our main code we extends this class and override doWork() method and return result Result.Success or failure

public class worker extends Worker {


public worker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {

return Result.success();
}
}

WorkRequest where declare the type of request may be OneTimeWorkRequest which execute for the single time and PeriodicWorkRequest which execute for exact period of time.

OneTimeWorkRequest obj = new OneTimeWorkRequest.Builder(worker.class).build();

WorkManager where we enque our work request

WorkManager.getInstance().enqueue(obj);

Chaining Of work where we enqueue our request one by one once completed other will start

WorkManager.getInstance().beginWith(obj).then(obj).then(obj).enqueue();

Serial Execution of multiple work where we execute work parallely

WorkManager.getInstance().beginWith(Arrays.asList(obj)).then(obj).enqueue();

WorkInfo where we collect information about the work using livedata observer

WorkManager.getInstance().getWorkInfoByIdLiveData(obj.getId())
.observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(@Nullable WorkInfo workInfo) {

//Displaying the status into TextView
Toast.makeText(getApplicationContext(),""+workInfo.getState().name(),Toast.LENGTH_LONG).show();
}
});

We can cancel work by calling work request get id

WorkManager.getInstance().cancelWorkById(obj.getId());