【发布时间】:2020-10-09 09:22:18
【问题描述】:
我想创建一个每天晚上 20 点发出通知的应用。为此,我需要为每天晚上 20 点执行的函数计时。解决这个问题的最佳方法是什么?我应该使用什么?
这是我要执行的功能:
private fun throwNotification() {
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val intent = Intent(applicationContext, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
notificationChannel = NotificationChannel(channelId, description, NotificationManager.IMPORTANCE_HIGH)
notificationChannel.enableLights(true)
notificationChannel.lightColor = Color.RED
notificationChannel.enableVibration(true)
notificationManager.createNotificationChannel(notificationChannel)
builder = Notification.Builder(this, channelId)
.setContentTitle("Test")
.setContentText("This is a test notification")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setChannelId(channelId)
notificationManager.notify(0, builder.build())
}
【问题讨论】:
-
您需要一个后台服务,该服务每次都运行,如果是晚上 20 点,则每小时检查一次并执行您的任务。
-
如果您想保证在我看来任务已执行,这就是解决方案。
-
不喜欢后台服务一直运行,有没有更好的解决方案?
-
如果您想要有保证的执行,这是正确的方法,或者尝试一下警报管理器。
标签: android kotlin push-notification notifications background-task