Androidx:WorkManager 的排队方法未运行 Worker



我想运行一个自定义Worker -NotificationWorker-显示在设备上的通知,然后设置日期&是时候使用WorkRequest

这是我加入WorkRequest的方法,它在UI类中被调用(在我的应用中,这是一个片段):

fun notifyUserAt(dt: LocalDateTime, title: String, text: String) {
    val epoch = DateUtil.toEpochMilli(dt)
    val now = DateUtil.toEpochMilli(
        ZonedDateTime.now(AppRepository.zoneId).toLocalDateTime()
    )
    val delay = epoch - now + 10
    val data: Data = Data.Builder()
        .putString(NOTIF_TITLE, title)
        .putString(NOTIF_CONTENT_TEXT, text)
        .putLong(NOTIF_DATETIME, epoch)
        .build()
    val constraints: Constraints = Constraints.Builder()
        .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
        .setRequiresCharging(false)
        .build()
    val notificationWork = OneTimeWorkRequestBuilder<NotificationWorker>()
        .setInputData(data)
        .setConstraints(constraints)
        .setInitialDelay(delay, TimeUnit.MILLISECONDS)
        .build()
    WorkManager.getInstance().enqueue(notificationWork)
}

请注意, delay 变量设置为 10 milliseconds(非常接近毫不延迟)。

这是我的工人班:

class NotificationWorker(val context: Context, params: WorkerParameters) :
    Worker(context, params) {
    override fun doWork(): Result {
        // Get data
        val title = inputData.getString(NOTIF_TITLE)
        val contentText = inputData.getString(NOTIF_CONTENT_TEXT)
        val epoch = inputData.getLong(NOTIF_DATETIME, 0L)
        // Build the notification
        val mNotification =
            NotificationCompat.Builder(context, NORMAL_CHANNEL_ID)
                .setContentTitle(title)
                .setContentText(contentText)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setContentIntent(overviewScreenIntent(context, epoch))
                .setAutoCancel(true)
                .build()!!
        val id = newNotificationId
        NotificationManagerCompat.from(context)
            .notify(id, mNotification)
        return Result.success()
    }

我在NotificationWorkerdoWork方法的最后一行中调试时设置了一个断点,但是该程序不在那里暂停。我想念什么吗?

没关系,通过将小图标设置为通过 setSmallIcon(icon)设置通知来解决。之后,通知完美显示。

最新更新