我一直在try 使用工作管理器和下载图像使用 retrofit ,并面临这个问题.
问题出在这段代码中
Result.Success( // This is creating problem
workDataOf(
WorkerConstants.IMAGE_URI to file.toUri().toString()
)
)
这是完整的功能代码.
import android.content.Context
import androidx.core.app.NotificationCompat
import androidx.core.net.toUri
import androidx.work.CoroutineWorker
import androidx.work.ForegroundInfo
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import com.gk.mycomposable.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import kotlin.random.Random
class DownloadWorker(
private val context: Context,
private val workerParam: WorkerParameters
) : CoroutineWorker(context, workerParam) {
override suspend fun doWork(): Result {
startForegroundService()
delay(5000L)
val response = FileAPI.instance.downloadImage()
response.body()?.let { body ->
return withContext(Dispatchers.IO) {
val file = File(context.cacheDir, "image.jpg")
val outputStream = FileOutputStream(file)
outputStream.use { stream ->
try {
stream.write(body.bytes())
} catch (e: IOException) {
return@withContext Result.failure(
workDataOf(
WorkerConstants.ERROR_MSG to e.localizedMessage
)
)
}
}
Result.Success( // This is creating problem
workDataOf(
WorkerConstants.IMAGE_URI to file.toUri().toString()
)
)
}
}
if (!response.isSuccessful){
if (response.code().toString().startsWith("5")){
return Result.retry()
}
return Result.failure(
workDataOf(
WorkerConstants.ERROR_MSG to "Network error"
)
)
}
return Result.failure(
workDataOf(
WorkerConstants.ERROR_MSG to "Unknown error"
)
)
}
private suspend fun startForegroundService() {
setForeground(
ForegroundInfo(
Random.nextInt(),
NotificationCompat.Builder(context, WorkerConstants.channelId)
.setSmallIcon(R.drawable.skull)
.setContentText("Downloading...")
.setContentTitle("Download in progress")
.build()
)
)
}
有人能告诉我为什么Success()
会显示这个警告吗?