我的闹钟管理器有问题。我的应用程序正在发送有关膳食的通知,我有 4 顿饭(早餐、午餐、晚餐、小吃)和时间选择器。如果我设置一顿饭的时间,它会发送通知,但如果我设置多于一顿饭的通知,它会发送所有通知。
例如我在 8:00 设置早餐通知,它会向我发送有关早餐的通知,但如果我在 8:05 设置另一个午餐通知,它会在 8:05 向我发送有关早餐和午餐的通知。
好吧,我已经尝试过。我尝试了很多事情:尝试将警报管理器中的标志更改为仅IMMUTABLE,尝试在启动之前取消警报(代码中的注释行),尝试在所有事情之后取消协程完成后,如果 timePicker 中的时间小于手机上的当前时间,则尝试将日期添加到日历中。提前谢谢你)
报警管理器代码:
class CCAlarmManager @Inject constructor(
private val alarmManager: AlarmManager,
private val mealTimeScreenRepositoryImpl: MealTimeScreenRepositoryImpl,
private val context: Context
) {
private val coroutineScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
fun scheduleMealAlarm(name: String) {
coroutineScope.launch {
mealTimeScreenRepositoryImpl.getMealTimeByName(name).collect { meal ->
val intent = Intent(context, CCAlarmReceiver::class.java).apply {
putExtra("mealName", meal.name)
}
val pendingIntent = PendingIntent.getBroadcast(
context,
meal.id,
intent,
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
)
//Cancel alarm if it exists, doesn't work
alarmManager.cancel(pendingIntent)
val hours = meal.time.split(":")[0].take(2).toInt()
val minutes = meal.time.split(":")[1].take(2).toInt()
val calendar = Calendar.getInstance().apply {
set(Calendar.HOUR_OF_DAY, hours)
set(Calendar.MINUTE, minutes)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
alarmManager.setRepeating(
AlarmManager.RTC_WAKEUP,
calendar.timeInMillis,
AlarmManager.INTERVAL_DAY,
pendingIntent,
)
}
}
}
fun cancelMealAlarm(name: String) {
coroutineScope.launch {
mealTimeScreenRepositoryImpl.getMealTimeByName(name).collect { meal ->
val pendingIntent = PendingIntent.getBroadcast(
context,
meal.id,
Intent(context, CCAlarmReceiver::class.java),
PendingIntent.FLAG_IMMUTABLE
)
alarmManager.cancel(pendingIntent)
}
}
}
}
广播接收器代码:
class CCAlarmReceiver: BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
val mealName = intent?.getStringExtra("mealName")
val notification = NotificationCompat.Builder(context, "cc_notifications")
.setSmallIcon(R.drawable.logo)
.setContentTitle("Eating time")
.setContentText("Time to eat $mealName")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build()
val notificationManager = context.getSystemService(Service.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(mealName.hashCode(), notification)
}
}
也许这篇文章会对某人有所帮助,但我解决了我的问题。我不知道为什么,但我的
alarmManager
正在创建具有相同 pendingIntent
id(id 不同)的警报。这就是为什么我在我的 ID 中添加了 hashCode()
。然后问题就消失了。
meal.id.toHashCode()