Android WorkManager:无法从 PeriodicWorkRequest 获取输出数据
2022-09-02 13:22:37
由于某些原因,我无法从Android WorkManager的Per periodicWorkRequest中获取输出数据。工作线程按预期定期运行,只是不返回任何数据。
我的主要活动:
@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);
}
}
});
}
我的服务器请求工作:
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 获取输出数据?我错了什么?