CoroutineWorker
的主要特点:
-
Kotlin 协程支持 :通过使用 Kotlin 协程,
CoroutineWorker
提供了更自然和可读的异步编程模型,避免了复杂的回调嵌套问题。 -
后台任务:它允许开发者在后台执行任务,比如数据同步、图片上传、定期执行任务等,而不需要担心任务被中断,即使应用关闭或重启,任务仍会在条件满足时继续执行。
-
持久性和约束条件 :与普通的后台线程不同,
CoroutineWorker
可以设置任务的执行条件,比如仅在设备充电、联网等条件满足时执行。WorkManager
会确保这些条件符合时,任务才会被执行。
Kotlin
package com.plcoding.globalsnackbarscompose.worker
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import androidx.work.workDataOf
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.File
import kotlin.math.roundToInt
class PhotoCompressionWorker(
private val appContex: Context,
private val params: WorkerParameters
) : CoroutineWorker(appContex, params) {
override suspend fun doWork(): Result {
return withContext(Dispatchers.IO) {
println("workder doWork")
val stringUri = params.inputData.getString(KEY_CONTENT_URI)
val compressThresHold = params.inputData.getLong(KEY_COMPRESSION_TH, 0L)
val uri = Uri.parse(stringUri)
val bytes = appContex.contentResolver.openInputStream(uri)?.use {
it.readBytes()
} ?: return@withContext Result.failure()
val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
var outputBytes: ByteArray
var quality = 100
do {
val outputStream = ByteArrayOutputStream()
outputStream.use { outputStream ->
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
outputBytes = outputStream.toByteArray()
quality -= (quality * 0.1).roundToInt()
}
} while (outputBytes.size > compressThresHold && quality > 5)
val file = File(appContex.cacheDir,"${params.id}.jpg")
file.writeBytes(outputBytes)
Result.success(
workDataOf(
KEY_RESULT_PATH to file.absoluteFile.toString()
)
)
}
}
companion object {
const val KEY_CONTENT_URI = "KEY_CONTENT_URI"
const val KEY_COMPRESSION_TH = "KEY_COMPRESSION_TH"
const val KEY_RESULT_PATH = "KEY_RESULT_PATH"
}
}
根据图片,因为不知道图片多大,还一次次的压缩,直到达到压缩的指标大小了,将文件写入文件
怎么启动这个woker呢
workManager = WorkManager.getInstance(applicationContext)
Kotlin
fun requestWorker(uri: Uri, workManager: WorkManager) {
val result = OneTimeWorkRequestBuilder<PhotoCompressionWorker>()
.setInputData(
workDataOf(
PhotoCompressionWorker.KEY_CONTENT_URI to uri.toString(),
PhotoCompressionWorker.KEY_COMPRESSION_TH to 1024 * 20L
)
).setConstraints(
Constraints(requiresStorageNotLow = true)
).build()
workManager.enqueue(result)
}
作为后台任务