如何在 WorkManager for Android 中创建一个带有参数的 Worker?

Posted

技术标签:

【中文标题】如何在 WorkManager for Android 中创建一个带有参数的 Worker?【英文标题】:How to create a Worker with parameters for in WorkManager for Android? 【发布时间】:2019-03-09 09:21:53 【问题描述】:

android 架构有一个新组件WorkManager。

来自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()

如何创建一个Worker 接受构造函数或doWork 中的参数?

【问题讨论】:

【参考方案1】:

在 Java 中:

传递参数如下:

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

你可以这样:

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();
    

希望它会明显有所帮助。

【讨论】:

【参考方案2】:

你可以像Bundle一样使用setInputData方法发送数据。

/***  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.)

    


欲了解更多信息,请访问link。

【讨论】:

如何访问Worker中的数据? params.getInputData().getString("file_path") 有没有办法发送非原始值作为参数? 要回答@Óscar 点,这里讨论如何将可序列化的 POJO 传递给 Worker ***.com/questions/51018299/… @Óscar 尝试使用 workDataOf 时要谨慎。尽管有其方法签名,但您不能传递除基元以外的任何内容,因为生成的 Data 对象只能包含基元或基元数组。如果您尝试传递其他任何内容,您将收到 IllegalArgumentException

以上是关于如何在 WorkManager for Android 中创建一个带有参数的 Worker?的主要内容,如果未能解决你的问题,请参考以下文章

WorkManager 系列课程 | MAD Skills

WorkManager 如何安排对 REST API 的 GET 请求?

WorkManager 如何用于小部件更新?

如何使用Workmanager / PeriodicWorkRequest保持时间间隔之间的数据

如何在 Android Jetpack Workmanager 中输入和输出 AN Object 数据?

从 FirebaseJobDispatcher 迁移到 AndroidX Workmanager 时:如何在 startWork 中返回 ListenableFuture? [复制]