Work Inputs
However, doWork()
would crash if we scheduled it this way. That comes back to those getInputData()
calls from our doWork()
method.
Often, our work needs data describing that work. In the case of DownloadWorker
, we need to know:
- the HTTPS URL to download from
- the name of the file to download to (where the file will be placed in
getCacheDir()
)
WorkManager
has a solution for this, via the Data
class (perhaps named after the android character in Star Trek properties) (or perhaps not).
Data
is a key-value store, one that very closely resembles PersistableBundle
. The values are simple primitives plus arrays of simple primitives. We can package information into a Data
, attach it to the work request, and then get that information from inside of doWork()
.
Reading the Data
is a matter of calling getInputData()
inside of doWork()
, then calling getter methods based on type (e.g., getString()
). Those getter methods take the key under which the data is stored as a parameter. Getters for primitive types (e.g., getInt()
, getBoolean()
) also have a second parameter to use for the default response, if there is nothing associated with that key in the Data
.
Putting Data
into a request is a matter of creating a Data
instance using a Data.Builder
, which contains the corresponding setter methods (e.g., putString()
):
OneTimeWorkRequest downloadWork=
new OneTimeWorkRequest.Builder(DownloadWorker.class)
.setInputData(new Data.Builder()
.putString(DownloadWorker.KEY_URL,
"https://commonsware.com/Android/Android-1_0-CC.pdf")
.putString(DownloadWorker.KEY_FILENAME, "oldbook.pdf")
.build())
.build();
WorkManager.getInstance().enqueue(downloadWork);
Here, we fill in the two values that the DownloadWorker
is expecting, using setInputData()
to attach the Data
to our OneTimeWorkRequest
.
Note that there is a 10KB limit on the size of the Data
. Data
is there mostly to provide identifiers, such as the URL and filename that we are using here. Use the Data
for unique information, stuff that the Worker
subclass cannot obtain from other sources (e.g., your database, your SharedPreferences
).
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.