【问题标题】:Android: How to detect how long workmanager is already in enqueue mode?Android:如何检测 workmanager 已经处于入队模式多长时间?
【发布时间】:2020-09-25 17:59:02
【问题描述】:

我想检测,特定作品在enqueue 模式下已经存在多长时间。我需要这些信息,以便通知用户他的状态(例如,当工作经理在enqueue mode 中超过 10 秒时 -> 取消工作 -> 通知用户他需要执行 X 以实现 Y)。像这样的:

伪代码

workInfo.observe(viewLifecylceOwner) {
    when(it.state) {
       WorkInfo.State.ENQUEUED -> if(state.enqueue.time > 10) cancelWork()
    }
}

我在任何地方都没有找到任何关于此的信息。这可能吗?

感谢每一个帮助。

【问题讨论】:

  • 我不相信这样的事情存在,你必须在启动时记录时间戳并自己跟踪
  • 您能否提供一个如何创建时间戳的链接?这对我来说是一个可能的解决方案:创建时间戳实时数据/流并观察它。
  • 只需调用System.currentTimeMills() 即可获得UTC 毫秒时间
  • 是的,但不幸的是,这还不够,因为我必须设置一个 MAX_TIME 并留意它..

标签: android kotlin kotlin-coroutines android-jetpack android-workmanager


【解决方案1】:

我已经设法创建了一个有点健壮的“Workmanager watcher”。我的意图如下:当 Workmanager 没有在 7 秒内完成时,告诉用户发生了错误。 Workmanager 本身永远不会被取消,而且我的功能甚至没有与 Workmanager 本身交互。这在 99% 的情况下都有效:

工人助手

object WorkerHelper {
private var timeStamp by Delegates.notNull<Long>()

private var running = false
private var manuallyStopped = false
private var finished = false

open val maxTime: Long = 7000000000L

// Push the current timestamp, set running to true
override fun start() {
    timeStamp = System.nanoTime()
    running = true
    manuallyStopped = false
    finished = false
    Timber.d("Mediator started")
}

// Manually stop the WorkerHelper (e.g when Status is Status.Success)
override fun stop() {
    if (!running) return else {
        running = false
        manuallyStopped = true
        finished = true
        Timber.d("Mediator stopped")
    }
}

override fun observeMaxTimeReachedAndCancel(): Flow<Boolean> = flow {
    try {
        coroutineScope {
            // Check if maxTime is not passed with => (System.nanoTime() - timeStamp) <= maxTime
            while (running && !finished && !manuallyStopped && (System.nanoTime() - timeStamp) <= maxTime) {
                emit(false)
            }
            // This will be executed only when the Worker is running longer than maxTime
            if (!manuallyStopped || !finished) {
                emit(true)
                running = false
                finished = true
                this@coroutineScope.cancel()
            } else if (finished) {
                this@coroutineScope.cancel()
            }
        }
    } catch (e: CancellationException) {
    }
}.flowOn(Dispatchers.IO)

然后在我的 Workmanager.enqueueWork 函数中:

fun startDownloadDocumentWork() {
    WorkManager.getInstance(context)
        .enqueueUniqueWork("Download Document List", ExistingWorkPolicy.REPLACE, downloadDocumentListWork)
    pushNotification()
}

private fun pushNotification() {
    WorkerHelper.start()
}

最后在我的 ViewModel 中

   private fun observeDocumentList() = viewModelScope.launch {
        observerWorkerState(documentListWorkInfo).collect {
            when(it) {
                is Status.Loading -> {
                    _documentDataState.postValue(Status.loading())

                    // Launch another Coroutine, otherwise current viewmodelscrope will be blocked
                    CoroutineScope(Dispatchers.IO).launch {
                        WorkerHelper.observeMaxTimeReached().collect { lostConnection ->
                            if (lostConnection) {
                                _documentDataState.postValue(Status.failed("Internet verbindung nicht da"))
                            }
                        }
                    }
                }
                is Status.Success -> {
                    WorkerHelper.finishWorkManually()
                    _documentDataState.postValue(Status.success(getDocumentList()))
                }
                is Status.Failure -> {
                    WorkerHelper.finishWorkManually()
                    _documentDataState.postValue(Status.failed(it.message.toString()))
                }
            }
        }
    }

我还创建了一个函数,将我的workmanager 的状态转换为我的自定义状态类:

状态

sealed class Status<out T> {
    data class Success<out T>(val data: T) : Status<T>()
    class Loading<T> : Status<T>()
    data class Failure<out T>(val message: String?) : Status<T>()

    companion object {
        fun <T> success(data: T) = Success<T>(data)
        fun <T> loading() = Loading<T>()
        fun <T> failed(message: String?) = Failure<T>(message)
    }
}

功能

suspend inline fun observerWorkerState(workInfoFlow: Flow<WorkInfo>): Flow<Status<Unit>> = flow {
    workInfoFlow.collect {
        when (it.state) {
            WorkInfo.State.ENQUEUED -> emit(Status.loading<Unit>())

            WorkInfo.State.RUNNING -> emit(Status.loading<Unit>())

            WorkInfo.State.SUCCEEDED -> emit(Status.success(Unit))

            WorkInfo.State.BLOCKED -> emit(Status.failed<Unit>("Workmanager blocked"))

            WorkInfo.State.FAILED -> emit(Status.failed<Unit>("Workmanager failed"))

            WorkInfo.State.CANCELLED -> emit(Status.failed<Unit>("Workmanager cancelled"))
        }
    }
}

【讨论】:

  • 如何从 WorkManager 获取 WorkInfo 流?我只看到 getWorkInfosByTagLiveData,但没有对应 Flow 的方法。
  • getWorkInfosByTagLiveData.asFlow()
  • 如果有人想知道,要使用asFlow(),你需要添加依赖:implementation("androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version")
猜你喜欢
  • 1970-01-01
  • 2014-03-30
  • 2012-09-24
  • 2019-01-07
  • 2012-04-13
  • 2017-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多