android - Android Worker 有时不发送通知
问题描述
背景:我们创建了一个用于跟踪您的工作时间的应用程序,您在到达时按“入住”,在您离开时按“退房” 。我们认为如果用户可以设置入住或退房提醒会很好。由于我们需要有关用户当前签到状态的数据来显示正确的文本,我们不能只安排通知,我们需要先从在线数据库中获取该数据,然后决定显示什么,因此我们需要工作经理。
有时,尽管有关后台工作成功的日志消息不会显示一个通知(签入时间),而另一个应该在(签出时间)显示之后显示的通知。
我正在使用带有最新更新 (Android 9) 的三星 Galaxy S9+。
我尝试通过亚行检查预定的工作。有时他们在那里有正确的延迟和一切,有时他们根本不在那里,但通知还是会到达,所以这并不是那么可靠。
在我所涵盖的每个案例中,我都使用调试器进行了调度,一切都按照我的预期进行了设置:新班次被添加到数组中并填充了预期的数据,工作安排在正确的时间。编辑时,旧作品被 UUID 取消,新作品被创建。删除时,工作被取消,班次设置为空。
首先,我需要为特定的班次安排工作。具有这些时间的预定通知的Shift
属性shiftFrom
和UUID。shiftTo
为了安排工作人员,我有一个NotificationScheduler
带有scheduleWeekly
方法的类,我可以在其中确定延迟,然后安排工作:
val sendNotificationRequest = PeriodicWorkRequestBuilder<NotificationsWorker>(7, TimeUnit.DAYS)
.setInputData(
workDataOf(
NotificationsWorker.TITLE_PARAM to title,
NotificationsWorker.CONTENT_PARAM to content,
NotificationsWorker.ACTION to action // this tells the worker wheter the user is supposed to check in or check out when it's triggered
)
)
.setInitialDelay(initialDelayMinutes, TimeUnit.MINUTES) // wanted time - current time converted to minutes
.build()
WorkManager.getInstance(context).enqueue(sendNotificationRequest)
触发时,它会调用NotificationsWorker
. 根据当前的签入状态以及用户是否应该签入或签出,我决定要在通知中显示哪些文本。此外,我创建的日志消息也会被记录——工作确实是在正确的时间触发的。
然后我使用这种方法发送通知:
private fun sendNotification(title: String, content: String) {
val notificationIntent = Intent(context, SplashActivity::class.java) // for when the notification is clicked
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
val intent = PendingIntent.getActivity(
context, 0,
notificationIntent, 0
)
val builder =
NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
.setSmallIcon(package.appname.R.drawable.ic_app_icon)
.setContentTitle(title)
.setContentText(content)
.setContentIntent(intent)
.setAutoCancel(true)
.setStyle(NotificationCompat.BigTextStyle().bigText(content))
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
with(NotificationManagerCompat.from(context)) {
notify(0, builder.build())
}
}
我期望通知从预定时间开始 +-10 分钟到达,而且大多数情况下就是这样,但有时它们根本没有到达,有时我会在非常奇怪的时间收到它们(例如,我有一个说我本来应该在周六 22:12 签到,但轮班安排在周一至周五 8 点到 16 点)。
此外,周六提到的通知以某种方式设法获取了有关我签到状态的数据,但我没有互联网连接,目前通知没有收到任何本地数据。
解决方案
推荐阅读
- r - 如何使用参数组合将 mapply 与长度不等的输入集一起使用?
- python - Python线程:如何限制活动线程数?
- java - 使用 VoiceInteractor 的代码时,应用程序因空指针异常而崩溃
- python - 比较熊猫系列中的元素后从列表中获取匹配的字符串
- php - 使用 PHP 8.0 或 PHP 7.4 连接到 MS SQL Server 2005
- crystal-reports - Crystal Reports:使用数据时间字段中的日期作为参数
- google-cloud-platform - 如何将 cloudbuild (GCP) 与 CodeCommit 集成
- python - 使用带有 .conf 文件的谷歌云日志记录处理程序
- testing - Testcafe 和 ids 以及自定义单选按钮的性能下降
- amazon-web-services - Cognito 用户池 Lambda 触发器权限