How to create a Worker with parameters for in WorkManager for Android?

26,569

Solution 1

You can use setInputData method to send data just like Bundle.

/***  Logic to set Data while creating worker **/
val compressionWork = OneTimeWorkRequest.Builder(CompressWorker::class.java)
val data = Data.Builder()
//Add parameter in Data class. just like bundle. You can also add Boolean and Number in parameter.
data.putString("file_path", "put_file_path_here")
//Set Input Data
compressionWork.setInputData(data.build())
//enque worker
WorkManager.getInstance().enqueue(compressionWork.build())


/*** Logic to get Data  ***/
class CompressWorker(context : Context, params : WorkerParameters)
    : Worker(context, params) {

    override fun doWork(): Result {

        //get Input Data back using "inputData" variable 
        val filePath =  inputData.getString("file_path")

        // Do the work here--in this case, compress the stored images.
        // In this example no parameters are passed; the task is
        // assumed to be "compress the whole library."
        myCompress()

        // Indicate success or failure with your return value:
        return Result.SUCCESS

        // (Returning RETRY tells WorkManager to try this task again
        // later; FAILURE says not to try again.)

    }

}

For more information visit this link.

Solution 2

In Java:

Pass params as follow:

    Constraints.Builder builder = new Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED);

    // Passing params
    Data.Builder data = new Data.Builder();
    data.putString("SyncMaster", syncModuleName);

    OneTimeWorkRequest syncWorkRequest =
            new OneTimeWorkRequest.Builder(SyncWorker.class)
                    .addTag("Sync")
                    .setInputData(data.build())
                    .setConstraints(builder.build())
                    .build();

    WorkManager.getInstance().enqueue(syncWorkRequest);

You can get like this:

public class SyncWorker extends Worker {

    private static final String TAG = "MyWorker";

    public SyncWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
        mContext = context;
    }

    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, "doWork for Sync");
        String syncTable = getInputData().getString("SyncMaster");
        return Result.success();
    }
}

Hope it will clearly help.

Share:
26,569
Joshua
Author by

Joshua

Updated on July 09, 2022

Comments

  • Joshua
    Joshua almost 2 years

    Android architecture has a new components WorkManager.

    From the example,

    class CompressWorker(context : Context, params : WorkerParameters)
        : Worker(context, params) {
    
        override fun doWork(): Result {
    
            // Do the work here--in this case, compress the stored images.
            // In this example no parameters are passed; the task is
            // assumed to be "compress the whole library."
            myCompress()
    
            // Indicate success or failure with your return value:
            return Result.SUCCESS
    
            // (Returning RETRY tells WorkManager to try this task again
            // later; FAILURE says not to try again.)
    
        }
    
    }
    
    val compressionWork = OneTimeWorkRequestBuilder<CompressWorker>().build()
    

    How can I create a Worker that accept parameters in constructor or doWork?

  • Joshua
    Joshua over 5 years
    How can I access the data in Worker?
  • Dhaval Patel
    Dhaval Patel over 5 years
    @Joshua you can use "inputData" to get your data back. Check above sample code. I have explained how to send "file_path" and how to retrieve it back.
  • Titto Jose
    Titto Jose over 5 years
    params.getInputData().getString("file_path")
  • Óscar
    Óscar about 5 years
    Is there any way to send non-primitive values as parameter?
  • YuTang
    YuTang over 4 years
    workDataOf(vararg pairs: Pair<String, Any?>): Data is also provided to use with kotlin extension function to like val data = workDataOf(key to value)
  • Marino
    Marino over 3 years
    To answer @Óscar point here's a discussion on how to pass a Serializable POJO to a Worker stackoverflow.com/questions/51018299/…
  • nkotula
    nkotula about 3 years
    @Óscar Be cautious about trying to use workDataOf. Despite its method signature, you can't pass anything other than primitives since the resulting Data object can only contain primitives or arrays of primitives. You will get an IllegalArgumentException if you try to pass anything else.