【问题标题】:How to create a Worker with parameters for in WorkManager for Android?如何在 WorkManager for Android 中创建一个带有参数的 Worker?
【发布时间】: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 中的参数?

【问题讨论】:

    标签: android kotlin android-architecture-components android-workmanager


    【解决方案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 stackoverflow.com/questions/51018299/…
      • @Óscar 尝试使用 workDataOf 时要谨慎。尽管有其方法签名,但您不能传递除基元以外的任何内容,因为生成的 Data 对象只能包含基元或基元数组。如果您尝试传递其他任何内容,您将收到 IllegalArgumentException
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2019-11-05
      • 2012-02-29
      • 1970-01-01
      • 1970-01-01
      • 2011-06-20
      • 2018-05-08
      相关资源
      最近更新 更多