16148

Android WorkManager: Cannot get output data from PeriodicWorkRequest

<h3>Question</h3>

For some reasons I cannot get output data from PeriodicWorkRequest of Android WorkManager. The worker runs periodically as expected, it just doesn't return any data.

My 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); } } }); }

My 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); }

The value from workInfo.getOutputData().getString is always null. Here's what I get in the log:

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

It's interesting that getting output data from OneTimeWorkRequest is working fine. If I switch from PeriodicWorkRequest to 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); } } });

, then I successfully receive the value from output data:

MainActivity: message: This is output message

I've tried enqueueing unique work and enqueueing by tag, but no luck. Have tried WorkManager 2.2.0 and 1.x, result is the same.

Am I missing something? Is it even possible to get output data from PeriodicWorkRequest? What do I wrong?


<h3>Answer1:</h3>

As per the WorkInfo documentation:

<blockquote>

Note that output is only available for the terminal states (WorkInfo.State.SUCCEEDED and WorkInfo.State.FAILED).

</blockquote>

For Periodic work, the same ID is reused for each run, meaning that the work never gets to SUCCEEDED - instead, the work transitions immediately back to ENQUEUED, waiting for the next periodic run. Therefore, what you're experiencing seems to be the expected behavior.

As you've seen, using one time work does not have this behavior, since the work actually gets to SUCCEEDED and each subsequent run (if your one time work were to reschedule the same type work) would have a new ID. The other alternative is to <em>not</em> use output data, but instead store the result of your periodic work in your own database.

来源:https://stackoverflow.com/questions/57845459/android-workmanager-cannot-get-output-data-from-periodicworkrequest

Recommend

  • D3 Arc With Chevron Shaped End
  • How, using sed, can one extract a regex-delimited range except for the last line?
  • Haskell: Why is (+), (-) part of Num typeclass?
  • offsetParent() in jQuery not returning expected relative-positioned ancestor
  • Android WebView loading blank when viewing html nested lists
  • Trying to understand setf + aref “magic”
  • Custom exception vs built in exception with very descriptive message
  • Dynamically changing a checkbox doesn't trigger onChange?
  • I want to get all objects except text object as an image from PDF using iTextSharp
  • CPanel does not allow using script to create file?
  • Combining isset and is_null fails when checking undefined object property
  • Is Win2D yet available in C++/WinRt?
  • Split string and numbers
  • openTSDB REST API is not storing data
  • xcode 9.0.1 / swift 4, No method declared with Objective-C selector 'onClick:forEvent:' [d
  • MySQL database structure for a webshop
  • Retrieve 3rd MAX salary in Hive
  • Add a value to a column of DASK data-frames imported using csv_read
  • Raw sockets in monotouch
  • How to use mixed C++ & .Net dll in node.js? (Error: abort() has been called)
  • Oracle BI Publisher - How to format numbers as text so that leading zeroes don't dissappear
  • Google Apps Script fails to generate image from EmbeddedChartBuilder
  • AWS RDS Parameter Group not changing MySQL encoding
  • Pandas vs matplotlib datetime
  • How to use array in autohotkey?
  • Generate and export point cloud from Project Tango
  • How to define something in JavaScript [closed]
  • Why is ordered choice in pyparsing failing for my use case?
  • Neo4j…how to get a visual representation of my data?
  • JavaScript Regex to Match Boundaries of Words with diacritics
  • How to turn off notice reporting in xampp?
  • Background transfer download task failed when app was closed
  • Bitrate JWplayer
  • Accessing Arguments, Workflow Variables from custom activities
  • Write to .csv file with PHP (Commas in Data Error)