运行 两个独立的工人

Running two separate workers

我正在尝试 运行 两个独立的 Worker,当我启动一个 Worker 时,我无法启动另一个 Worker。我觉得我可能缺少一些东西来关闭工人,让我开始另一个工人。

片段

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();
    }
}

工人二

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();
    }
}

可能是您的工人Constraint与您设备的当前状况不匹配。请检查您的 Constraint.

你的代码在我的测试中运行良好,两个工人都在做他们的工作,

从评论中得知,过滤 logcat 不正确,因此您只能从一个 Worker 获取日志,同时过滤掉另一个 Worker 的日志。

这可以通过在两个 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 应该只工作一次,如果你想重复工作,你可以在按钮的回调中实例化 OneTimeWorkRequest 对象,所以它将是一个带有新工作请求

btnOne.setOnClickListener(view -> {
    OneTimeWorkRequest workerOne = new OneTimeWorkRequest.Builder(WorkerOne.class)
            .setConstraints(myConstraints)
            .addTag("WorkerOne")
            .build();

    WorkManager.getInstance(getActivity()).enqueue(workerOne);
});