我有3个任务A,B和C。我想观察此链的实时数据,并有一个进度条,显示正在进行的工作,完成工作后,应禁用进度条。
// One Time work for A class
OneTimeWorkRequest Awork = new OneTimeWorkRequest
.Builder(A.class)
.setConstraints(Miscellaneous.networkConstraint())
.addTag("A")
.build();
//same for B and C
//work chain
WorkContinuation syncChain = WorkManager.getInstance()
.beginWith(Awork)
.then(Bwork)
.then(Cwork);
syncChain.enqueue();
答案 0 :(得分:3)
您可以使用mWorkManager.getWorkInfosByTagLiveData(TAG_OUTPUT);
方法来恢复WorkRequest的状态,如WorkManager codelab所示。
这使您可以从WorkRequest中检索状态,作为带有以下可能状态的“ WorkInfo.State”枚举:
但是,我不确定这是否给您足够的粒度来管理进度条。
如上所述,检索信息使您可以灵活地为每个WorkRequest检索WorkInfo。
另外,您可以检索WorkContinuation
的WorkInfo
列表:
public abstract LiveData<List<WorkInfo>> getWorkInfosLiveData
答案 1 :(得分:1)
只是通过一个简单的例子来说明答案
final int TASK_COUNT = 4;
mProgressBar = findViewById(R.id.progressbar);
mProgressBar.setMax(TASK_COUNT);
// One Time work for A class
OneTimeWorkRequest Awork = new OneTimeWorkRequest
.Builder(A.class)
.setConstraints(Miscellaneous.networkConstraint())
.addTag("A")
.build();
//same for B and C
//work chain
WorkContinuation syncChain = WorkManager.getInstance()
.beginWith(Awork)
.then(Bwork)
.then(Cwork);
syncChain.enqueue();
syncChain.getWorkInfosLiveData().observe(this, new Observer<List<WorkInfo>>() {
@Override
public void onChanged(List<WorkInfo> workInfos) {
int finishedCount = 0;
for (WorkInfo workInfo : workInfos) {
if (workInfo.getState().isFinished() && workInfo.getState() == WorkInfo.State.SUCCEEDED) {
finishedCount++;
}
}
mProgressBar.setProgress(finishedCount);
if (finishedCount == workInfos.size()) {
mProgressBar.setEnabled(false);
}
}
});
答案 2 :(得分:0)
您可以使用enqueue()方法返回的“ Operation”接口,该方法具有两个方法getState()和getResult()
fun enqueue(requests: List<WorkRequest>): Operation
fun cancelWorkById(id: UUID): Operation
interface Operation{
fun getState(): LiveData<Operation.State>
fun getResult(): ListenableFuture<Operation.State.SUCCESS>
}
您可以使用getState()函数跟踪进度和中间状态,而getResult()函数将仅返回终端状态。即。成功或失败。