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

时间:2018-10-04 04:26:55

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

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中的参数?

2 个答案:

答案 0 :(得分:13)

您可以使用setInputData方法来发送数据,就像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.)

    }

}

有关更多信息,请访问此link

答案 1 :(得分:1)

在Java中:

传递参数如下:

select username, sum(amount) 
from my_table 
group by username
order by sum(amount) DESC 
limit 50 

您可以这样获得:

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

希望这显然会有所帮助。