I'm trying to run two separate Workers, When I start one worker I'm unable to start the other worker. I feel like I might be missing something to close the worker allowing me to start another worker.
Fragment
Constraints myConstrainst = new Constraints.Builder()
.setRequiredNetworkType(NetworkType.UNMETERED)
.build();
OneTimeWorkRequest workerOne = new OneTimeWorkRequest.Builder(WorkerOne.class)
.setConstraints(myConstraints)
.addTag("WorkerOne")
.build();
OneTImeWorkRequest workerTwo = new OneTimeWorkRequest.Builder(WorkerTwo.class)
.setConstraints(myConstrains)
.addTag("WorkerTwo")
.build();
btnOne.setOnClickListener(view -> {
WorkMananger.getInstance(getActivity()).enqueue(workerOne);
});
btnTwo.setOnClickListener(view -> {
WorkManager.getInstance(getActivity()).enqueue(workerTwo);
});
WorkerOne
public class WorkerOne extends Worker {
public WorkerOne(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@Override
public Result doWork() {
for(int i = 0; i < 5; i++) {
Log.d("WorkerOne", "doWork " + i);
SystemClock.sleep(1000);
}
return Result.success();
}
}
WorkerTwo
public class WorkerTwo extends Worker {
public WorkerTwo(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
@Override
public Result doWork() {
for(int i = 0; i < 5; i++) {
Log.d("WorkerTwo", "doWork " + i);
SystemClock.sleep(1000);
}
return Result.success();
}
}
Your code is working fine with my test, both workers do their job,
As got from comments, filtering logcat not that right so you just get logs from one Worker while filtering out the other Worker's log.
This can be confirmed by debugging code with break points in both doWork().
EDIT
This is a request from comments not relevant to the question
I press btnOne to run workerOne and wait for the work to finish. If I press btnOne a second time nothing happens
OneTimeWorkRequest
is supposed to work only once, if you want to repeat the work you can instantiate the OneTimeWorkRequest
object within the callback of your button, so it will be a new object with a new work request
btnOne.setOnClickListener(view -> {
OneTimeWorkRequest workerOne = new OneTimeWorkRequest.Builder(WorkerOne.class)
.setConstraints(myConstraints)
.addTag("WorkerOne")
.build();
WorkManager.getInstance(getActivity()).enqueue(workerOne);
});