Home > Software design >  Alarm isn't executed on Android
Alarm isn't executed on Android

Time:02-23

I have an android app where I try to set an alarm. My code inside activity:

fun setAlarm() {
    alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
    val intent = Intent(this, NotificationReceiver::class.java)
    pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_IMMUTABLE)

    alarmManager!!.set(AlarmManager.RTC_WAKEUP, /*calculateAlarmTime()*/1, pendingIntent)

    Timber.i("setAlarm executed")
}

I set this alarm, calling setAlarm method. This is my NotificationReceiver class:

public class NotificationReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Timber.i("onReceive called");
    }
}

Why I have only "setAlarm executed" in logcat, and not "onReceive called"? I set alarm to 1 millisecond and it should trigger immeditately. Why nothing happens?

CodePudding user response:

You set the AlarmManager with RTC_WAKEUP, so you should supply the exact date and time. Instead you set the time to 1 ms, which is interpreted as 1ms after 1-1-1970, 00h00m00s. If you want to use an relative time from setting the alarmManager you should get the current RTC time, add a few seconds and set the alarmManager with that time. As this method is inexact, allow a few seconds leeway. See here for description RTC_WAKEUP

CodePudding user response:

Your second parameter is wrong. It isn't how long from now you want the alarm to occur, it's the Unix timestamp of when you want it to occur. So 1 would have happened back in 1970. You would need to, at minimum, go System.currentTimeMillis() 1. Although that may well cause race conditions, I wouldn't count on an alarm being set for less than a second in the future working.

  • Related