CoroutineWorker 压缩图片示例

CoroutineWorker 的主要特点:

  1. Kotlin 协程支持 :通过使用 Kotlin 协程,CoroutineWorker 提供了更自然和可读的异步编程模型,避免了复杂的回调嵌套问题。

  2. 后台任务:它允许开发者在后台执行任务,比如数据同步、图片上传、定期执行任务等,而不需要担心任务被中断,即使应用关闭或重启,任务仍会在条件满足时继续执行。

  3. 持久性和约束条件 :与普通的后台线程不同,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)

    }

作为后台任务

相关推荐
Exploring12 小时前
从零搭建使用 Open-AutoGML 搜索附近的美食
android·人工智能
ask_baidu13 小时前
Doris笔记
android·笔记
lc99910213 小时前
简洁高效的相机预览
android·linux
hqk13 小时前
鸿蒙ArkUI:状态管理、应用结构、路由全解析
android·前端·harmonyos
消失的旧时光-194314 小时前
从 C 链表到 Android Looper:MessageQueue 的底层原理一条线讲透
android·数据结构·链表
方白羽14 小时前
Android 中Flags从源码到实践
android·app·客户端
深蓝电商API14 小时前
从数据采集到商业变现:网络爬虫技术的实战与边界
android·爬虫
恋猫de小郭16 小时前
再次紧急修复,Flutter 针对 WebView 无法点击问题增加新的快速修复
android·前端·flutter
李慕婉学姐16 小时前
【开题答辩过程】以《基于Android的健康助手APP的设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
android·java·mysql