由于某些原因,我无法从Android WorkManager的PeriodicWorkRequest获取输出数据。工作程序按预期定期运行,只是不返回任何数据。
我的MainActivity:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
schedulePeriodicRequests();
}
public void schedulePeriodicRequests() {
PeriodicWorkRequest workRequest = new PeriodicWorkRequest.Builder(ServerRequestsWorker.class, 15, TimeUnit.MINUTES)
.build();
WorkManager workManager = WorkManager.getInstance(MainActivity.this);
workManager.enqueue(workRequest);
workManager.getWorkInfoByIdLiveData(workRequest.getId())
.observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(@Nullable WorkInfo workInfo) {
if (workInfo != null) {
Log.d(LOG_TAG, "WorkInfo received: state: " + workInfo.getState());
String message = workInfo.getOutputData().getString(ServerRequestsWorker.KEY_MESSAGE);
Log.d(LOG_TAG, "message: " + message);
}
}
});
}
我的ServerRequestsWorker:
public static final String KEY_MESSAGE = "message";
@NonNull
@Override
public Result doWork() {
Log.d(LOG_TAG, "Worker works");
Data outputData = new Data.Builder()
.putString(KEY_MESSAGE, "This is output message")
.build();
return Result.success(outputData);
}
workInfo.getOutputData()。getString中的值始终为null。 这是我在日志中得到的:
MainActivity: WorkInfo received: state: ENQUEUED
MainActivity: message: null
ServerRequestsWorker: Worker works
WM-WorkerWrapper: Worker result SUCCESS for Work [ id=5f2beba8-c8bf-4f07-b4ee-e876e95d3cdb, tags={ com.anshmidt.pricemonitor.ServerRequestsWorker } ]
MainActivity: WorkInfo received: state: RUNNING
MainActivity: message: null
MainActivity: WorkInfo received: state: ENQUEUED
MainActivity: message: null
有趣的是,从OneTimeWorkRequest获取输出数据工作正常。 如果我从PeriodicWorkRequest切换到OneTimeWorkRequest:
OneTimeWorkRequest serverScraperWorkRequest = new OneTimeWorkRequest.Builder(ServerRequestsWorker.class)
.build();
WorkManager workManager = WorkManager.getInstance(MainActivity.this);
workManager.enqueue(serverScraperWorkRequest);
workManager.getWorkInfoByIdLiveData(serverScraperWorkRequest.getId())
.observe(this, new Observer<WorkInfo>() {
@Override
public void onChanged(@Nullable WorkInfo workInfo) {
if (workInfo != null) {
Log.d(LOG_TAG, "WorkInfo received: state: " + workInfo.getState());
String message = workInfo.getOutputData().getString(ServerRequestsWorker.KEY_MESSAGE);
Log.d(LOG_TAG, "message: " + message);
}
}
});
,然后我成功地从输出数据中接收了值:
MainActivity: message: This is output message
我尝试加入独特的工作并按标签加入,但没有运气。 尝试过WorkManager 2.2.0和1.x,结果是相同的。
我想念什么吗?甚至可以从PeriodicWorkRequest获取输出数据吗?我怎么了?
答案 0 :(得分:0)
请注意,输出仅适用于终端状态(WorkInfo.State.SUCCEEDED和WorkInfo.State.FAILED)。
对于定期工作,每次运行都会重复使用相同的ID,这意味着工作永远不会到达SUCCEEDED
-相反,工作会立即转换回ENQUEUED
,等待下一次定期运行。因此,您正在经历的似乎是预期的行为。
如您所见,使用一次工作没有这种行为,因为工作实际上到达了SUCCEEDED
,并且随后的每次运行(如果您的一次工作是为了重新计划同一类型的工作)一个新的ID。另一种选择是不使用输出数据,而是将定期工作的结果存储在自己的数据库中。