由于某些原因,我无法从 Android WorkManager 的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);
}
,然后我成功收到输出数据的值:
MainActivity: message: This is output message
我尝试过将独特的工作排队并按标签排队,但没有运气。尝试过WorkManager 2.2.0和1.x,结果是一样的。
我错过了什么吗?是否有可能从PeriodicWorkRequest 获取输出数据?我有什么错吗?
一只甜甜圈
胡说叔叔
相关分类