Android WorkManager Check if Work Is in Queue or Running

May 14, 2019
getWorkInfos example

NOTE:

Dependencies

dependencies {
    // https://developer.android.com/jetpack/androidx/releases/work
    def work_version = '2.0.1'
    implementation "androidx.work:work-runtime-ktx:$work_version"

    // https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-android
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.1'
    // https://mvnrepository.com/artifact/org.jetbrains.kotlinx/kotlinx-coroutines-guava
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-guava:1.2.1'
}

Code

suspend fun check(workName: String) {
    Timber.d("$workName.check")
    val workManager = WorkManager.getInstance()

    val workInfos = workManager.getWorkInfosForUniqueWork(workName).await()
    if (workInfos.size == 1) {
        // for (workInfo in workInfos) {
        val workInfo = workInfos[0]
        Timber.d("workInfo.state=${workInfo.state}, id=${workInfo.id}")
        if (workInfo.state == WorkInfo.State.BLOCKED || workInfo.state == WorkInfo.State.ENQUEUED || workInfo.state == WorkInfo.State.RUNNING) {
            Timber.d("isAlive")
        } else {
            Timber.d("isDead")

        }
    } else {
        Timber.d("notFound")
    }
}

NOTE: What is WorkInfo.State.BLOCKED?

From this source

BLOCKED : This state occurs only if the work is in a chain and is not the next work in the chain.

ENQUEUED : Work enters this state as soon as the work is next in the chain of work and eligible to run. This work may still be waiting on Constraints to be met.

RUNNING : In this state, the work is actively executing. For Workers, this means the doWork() method has been called.

Usage

val WORK_NAME = ...
check(WORK_NAME)
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.