由于某些原因,我无法从Android WorkManager的PeriodicWorkRequest中获取输出数据。worker按预期定期运行,只是不返回任何数据。
我的MainActivity:
我的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获取输出数据是否可能?我做错了什么?