NOTE:
- In this example, I check WorkInfo using unique work name from Android Schedule Daily Repeating/Reminder Alarm at Specific Time With WorkManager example. Since I am using
workManager.enqueueUniqueWork(REMINDER_WORK_NAME, ExistingWorkPolicy.REPLACE, workRequest)
, I can be sure there is only oneWorkInfo
for this unqiue work name. - I am using kotlinx-coroutines-guava to convert
ListenableFuture
from WorkManager.getWorkInfosForUniqueWork to kotlin coroutines suspend function. - If you need to continuously listen to
WorkInfo
changes, you might want to trygetWorkInfosForUniqueWorkLiveData
.
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)