gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:37:07 26 4
gpt4 key购买 nike

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

最佳答案

你可以像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 .

关于android - 如何在 WorkManager for Android 中创建一个带有参数的 Worker?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52639001/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com