如何在实现WorkManger时将字节数组发送到Worker class?



我正在尝试将字节数组作为输入数据发送到WorkRequest中的Worker Class。有没有办法发送字节数组并在工人类中接收相同的字节数组?

我尝试发送IntArray,我能够达到结果。

实现:

//work request
val workRequest = OneTimeWorkRequest.Builder(MyWroker::class.java)
.setInputData(createInputData())
.build()
//create Input Data for work request
fun createInputData(): Data {
return Data.Builder()
.putString(FIRST_KEY, "My value")
.putInt(SECOND_KEY, 5)
.putByteArray(getByteArray())
.build()
}
I am getting an error cannot resolve method getByteArray(). I have read the documentation of Data class and there is no such method available.

在 WorkManager v2.1.0-alpha01 中添加了将字节和字节数组存储和检索到Data对象的支持。

您可以添加 WorkManager 的 KTX 并在工作请求中使用OneTimeWorkRequestBuilder<>()workDataOf()(或使用Data.Builder对象的putByteArray()方法):

val workRequest = OneTimeWorkRequestBuilder<MyWorker>()
.setInputData(createInputData())
.build()
private fun createInputData() = workDataOf(
FIRST_KEY to "My value", 
SECOND_KEY to byteArrayOf(0x2E, 0x38))

然后使用以下方法检索工作线程中的字节数组:

class MyWorker(ctx: Context, params: WorkerParameters) : Worker(ctx, params) {
override fun doWork(): Result {
val myByteArray = inputData.getByteArray()
// Do something with the ByteArray
Result.success()
}
}

相关内容

  • 没有找到相关文章

最新更新