Set a background alarm for the near future Android

73 views Asked by At

Please help me solve the problem with creating an alarm clock in Android.

My application needs to notify the user of an event at the time specified by him. These events happen in 5-10 minutes.

The first thing I tried to do was use the AlarmManager and its setExactAndAllowWhileIdle and set Alarm Clock methods. This works while the device is active, but the alarms don't go off when the device is in sleep mode. At the same time, as soon as I touch the device, the alarm clock worked. It doesn't suit me.

Then I tried using the Foreground Service. But the service also stops when the phone goes to sleep mode.

I also tried using wakelock, but the service is suspended anyway.

Is there any way to create an accurate alarm clock that will go off 5-10 minutes after it is set when the phone is in sleep mode?

I have been trying to solve this problem for a week now and there is no result. Please help me figure it out.

1

There are 1 answers

0
MohamedMab On

i have faced the same problem before setExactAndAllowWhileIdle() is designed to fire while the phone is in sleep mode but it will not wake it up and it hass some restrictions so it's not really exact try using setAlarmClock() this one is designed to to make the system exits sleep mode before the alarm fires code example:

val intent =
    Intent(context, AlarmReceiver::class.java).apply {

        addFlags(Intent.FLAG_FROM_BACKGROUND)
    }

alarmManager.setAlarmClock(
    AlarmManager.AlarmClockInfo(
        LocalDateTime
            .now()
            .atZone(ZoneId.systemDefault())
            .toEpochSecond() * 1000 + alarmItem.alarmIn * 1000,
        null,
    ),
    PendingIntent.getBroadcast(
        context,
        alarmItem.id.hashCode(),
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT or 
         PendingIntent.FLAG_IMMUTABLE,
    ),

This article explain this topic well : https://medium.com/@igordias/android-scheduling-alarms-with-precise-delivery-time-using-alarmmanager-75c409f3bde0

  • another thing you need to consider when using alarm manager when the device is rebooted the system will cancel all alarms to solve that you need to save those alarms using sqldelight for example and adding a broadcast receiver to schcedule them again when the device is rebooted

  • also using foreground service like you did is needed and do not forget to use broadcast receiver to receive those alarms