Android alarm manager with multiple pending intent

2019-08-26 03:08发布

So I have such app where you can create multiple journals and I want to set reminders for each journal. For example in one of the journals I set reminder to repeat every week on Tuesdays and Fridays and then in another journal I want to set different reminder on same days how can I do so that reminders wouldn't cancel each other? Because I cannot set one Alarm manager to repeat on different days I'm setting multiple alarm managers for each selected day with different requestCodes, but then if I set for other journal alarm managers with same requestCodes they cancel previous reminders. How could I solve this? (User can add multiple journals so different broadcast receivers are not an option)

fun setJournalReminder(context: Context, cls: Class<*>, hour: Int, minute: Int, day: Int){


        val calendar = Calendar.getInstance()
        val setCalendar = Calendar.getInstance().apply {
            timeInMillis = System.currentTimeMillis()
            set(Calendar.HOUR_OF_DAY, hour)
            set(Calendar.MINUTE, minute)
            set(Calendar.SECOND, 0)
        }

        when (day) {
            1 -> setCalendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
            2 -> setCalendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY)
            3 -> setCalendar.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY)
            4 -> setCalendar.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY)
            5 -> setCalendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY)
            6 -> setCalendar.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY)
            7 -> setCalendar.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY)
        }

        if (setCalendar.before(calendar))
            setCalendar.add(Calendar.DATE, 1)

        val receiver = ComponentName(context, cls)
        val pm = context.packageManager

        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP)

        val intent = Intent(context, cls)
        val pendingIntent = PendingIntent.getBroadcast(context, day, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        val alarmManager = context.getSystemService(ALARM_SERVICE) as AlarmManager

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, setCalendar.timeInMillis, AlarmManager.INTERVAL_DAY * 7, pendingIntent)

}

1条回答
来,给爷笑一个
2楼-- · 2019-08-26 03:56

you are using the day as a requestCode, so for the same day the pending intent will be updated. I think that you should use a combination of the day and a journalId to create your RequestCode(Request Code must be unique for a Journal and Day)

We could add the request code to Intent action to make Intent.filterEquals always false...

查看更多
登录 后发表回答