Is there a way to get the remaining initial delay for pending UniqueWork from the Android WorkManager?

Viewed 81

I have this usecase where an user can receive a FCM data message which in turn sets or update an UniqueWorkRequest for a future notification on the device of the user. But reading the documentation shows that: "FCM messages does not guarantee the order of delivery."

Is there a way of getting how much time there is left for a pending UniqueWorkRequest? That way I can can check if the request should be updated with the new data from FCM. In this case I want to ensure that the UniqueWorkRequest matches the latest date. See my current code below.

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    if (remoteMessage.data.isNotEmpty()) {
        with(remoteMessage.data) {
            val taskId = remoteMessage.data["TASK_ID"].toString()
            val taskDateTime: Long = get("TASK_START_DATE").toString().toLong()
            val taskTimeZone: String = get("TASK_TIMEZONE").toString()
            val taskDescription = get("TASK_DESCRIPTION").toString()

            val zonedDateTime = Instant
                .ofEpochMilli(taskDateTime)
                .atZone(ZoneId.of(taskTimeZone))

            if (zonedDateTime.isBefore(ZonedDateTime.now())) {
                handleNow(taskId, taskDescription) // trigger notification now
            } else {
                scheduleJob(taskId, zonedDateTime, taskDescription)
            }
        }
    }
}


fun scheduleJob(
    taskId: String,
    taskDateTime: ZonedDateTime,
    taskDescription: String
) {
    // calculate future delay
    val delay = max(0L, Duration.between(ZonedDateTime.now(), taskDateTime).toMillis())

    val workRequest = OneTimeWorkRequest.Builder(NotificationWorker::class.java)
        .setInitialDelay(delay, TimeUnit.MILLISECONDS)
        .build()

    // This should always represent the most recent taskDateTime
    workManager.enqueueUniqueWork(taskId, ExistingWorkPolicy.REPLACE, workRequest)
}
0 Answers
Related