问题描述
我想创建一个每天晚上20点发出通知的应用程序。为此,我需要安排一个每天20点执行的函数的时间。解决此问题的最佳方法是什么?我该怎么用?
这是我要执行的功能:
private fun throwNotification() {
notificationmanager = getSystemService(Context.NOTIFICATION_SERVICE) as notificationmanager
val intent = Intent(applicationContext,MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this,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点执行。
- #1应该每天重复一次。
- 即使应用已关闭,也应推送通知。
- 以上问题与设备是否重新启动无关。
我发现正在遵循的解决方案,要求该应用程序至少应启动一次。
#1〜3可以由AlarmManager实现。 在应用首次启动时,请调用以下代码来注册 alarmIntent 。
private var alarmMgr: AlarmManager? = null
private lateinit var alarmIntent: PendingIntent
alarmMgr = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
alarmIntent = Intent(context,YourAlarmReceiver::class.java).let { intent ->
PendingIntent.getBroadcast(context,intent,0)
}
// Set the alarm to start at 20:00.
val calendar: Calendar = Calendar.getInstance().apply {
timeInMillis = System.currentTimeMillis()
set(Calendar.HOUR_OF_DAY,20)
set(Calendar.MINUTE,0)
set(Calendar.SECOND,0)
}
// setRepeating() lets you specify a precise custom interval--in this case,// 1 day.
alarmMgr?.setRepeating(
AlarmManager.RTC_WAKEUP,calendar.timeInMillis,1000 * 60 * 60 * 24,alarmIntent
)
在这里, alarmIntent 将在每20点调用 YourAlarmReceiver 的onReceive()。 因此,您只需要在此onReceive()内部调用 throwNotification()。
#4也很简单,可以通过监听BOOT_COMPLETED事件来实现。