Repeating alarm manager that fires in doze mode

78 Views Asked by At

My app utilizes a alarm manager function the when fired runs a broadcaster, it is set to repeat daily at 7am using calendar.

Here is my current code:

        val mIntent = Intent(this, MyReceiver::class.java)

        val calendar: Calendar = Calendar.getInstance()
        calendar.timeInMillis = System.currentTimeMillis()
        calendar.set(Calendar.HOUR_OF_DAY, 7)
        calendar.set(Calendar.MINUTE, 0)
        if (calendar.timeInMillis < System.currentTimeMillis()) {
            calendar.add(Calendar.DAY_OF_MONTH, 1)
        }
        
        val mPendingIntent = PendingIntent.getBroadcast(this, 1, mIntent, PendingIntent.FLAG_UPDATE_CURRENT
        )
        val mAlarmManager = this
            .getSystemService(Context.ALARM_SERVICE) as AlarmManager
        mAlarmManager.setRepeating(
            AlarmManager.RTC_WAKEUP, calendar.timeInMillis,1000*60*60*24, mPendingIntent,
        )

I know doze mode effects alarms and I think it's causing my receiver to run late/not fully. So I would like to bypass this. I know I should use setExactAndAllowWhileIdle but this doesn't work with my calendar repeating method. I was wondering if there was something like a 'setRepeatingAndAllowWhileIdle' function or something I could use? But if not, how would I achieve a optimal way of doing this?

1

There are 1 best solutions below

1
Duy Anh On

u can use setExactAndAllowWhileIdle()