我的任务是在特定时间制定每天的通知时间表。目前我有当前的实现:
fun scheduleRepeatingRTCNotification(context: Context, hour: Int, min: Int) {
val calendar: Calendar = Calendar.getInstance()
calendar.timeInMillis = System.currentTimeMillis()
calendar.set(Calendar.HOUR_OF_DAY, hour)
calendar.set(Calendar.MINUTE, min)
calendar.set(Calendar.SECOND, 0)
val intent = Intent(context, AlarmReceiver::class.java)
alarmIntentRTC = PendingIntent.getBroadcast(
context,
ALARM_TYPE_RTC,
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
alarmManagerRTC = context.getSystemService(ALARM_SERVICE) as AlarmManager
alarmManagerRTC!!.setRepeating(
AlarmManager.RTC,
calendar.timeInMillis, AlarmManager.INTERVAL_DAY, alarmIntentRTC
)
}
还有我的广播接收器类:
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val intentToRepeat = Intent(context, MainActivity::class.java)
intentToRepeat.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
val pendingIntent = PendingIntent.getActivity(
context,
NotificationHelper.ALARM_TYPE_RTC,
intentToRepeat,
PendingIntent.FLAG_UPDATE_CURRENT
)
val repeatedNotification: Notification =
buildLocalNotification(context, pendingIntent).build()
NotificationHelper.getNotificationManager(context)
.notify(NotificationHelper.ALARM_TYPE_RTC, repeatedNotification)
}
除非应用程序被终止,否则此代码有效,当应用程序终止时,通知仅在应用程序启动时出现。即使应用程序被杀死,有没有办法让通知出现?我尝试了工作管理器、服务,到处都是相同的行为。