I have a problem with my alarm manager. My app is sending notifications about meals, i have 4 meals(breakfast, lunch, dinner, snack) and time pickers for them. If i set time for 1 meal, it will send notification for it, but if i set notifications for more than 1 meal, it sends notififications for all of them.
For example i set notification for breakfast at 8:00 it will send me notification about breakfast, but if i set another notification for lunch at 8:05 it will send me notification about breakfast and lunch at 8:05.
Ok, what i have tried. I have tried a lot of things: tried to change flags in alarm manager to only IMMUTABLE, tried to cancel alarm before start it(commented line in code), tried to cancel coroutine after all things have done, tried to add day to calendar if time in timePicker smaller than currentTime on Phone. Thank you in advance)
AlarmManager code:
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)
}
}
}
}
Broadcast receiver code:
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)
}
}