Alarm Manager fire early but not to set milliseconds

26 Views Asked by At
private void fireAlarmAt(int id,int year,int mnth,int day,int hour,int min,int sec) {
        AlarmManager alarmMgr;
        PendingIntent alarmIntent;
        alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
        if (Build.VERSION.SDK_INT >= 31)
            alarmIntent = PendingIntent.getBroadcast(getApplicationContext(),id,intent,PendingIntent.FLAG_IMMUTABLE);
        else
            alarmIntent = PendingIntent.getBroadcast(getApplicationContext(),id, intent, PendingIntent.FLAG_ONE_SHOT);
      
         // Set the alarm to start 
        Calendar calendar = Calendar.getInstance();
        
        Calendar calset = (Calendar) calendar.clone();
        calset.setTimeInMillis(System.currentTimeMillis());
        calset.set(Calendar.HOUR_OF_DAY, hour);
        calset.set(Calendar.MINUTE, min);
        calset.set(Calendar.SECOND, 0);
    
        Calendar calNow = (Calendar) calendar.clone();
        
        long remainTime  = calset.getTimeInMillis() - calNow.getTimeInMillis();
      
      
        alarmMgr.set(AlarmManager.RTC_WAKEUP,remainTime, alarmIntent);
        
    }
  • Alarm Trigger is weird if time remaining is 5 mins but fires early within 20 secs
  • Any wrong thing in the code
  • Here param id is used for multiple Alarm create
1

There are 1 best solutions below

0
Gabe Sechan On

Alarms are not exact. This is to save battery power- it batches requests to wake up and use the CPU so that they all occur at once causing less drain. So yes, occurring a few seconds early is not unexpected, and in the majority of usecases is ok. If you need more accuracy, use setExact or setExactAndAllowWhileIdle instead of set.

Also- no timer on any consumer OS is exact to the millisecond. For that you'd need a real time OS, which is generally only used for specific embedded hardware uses. Android and Linux are not real time, and thus will not promise to schedule your process to the millisecond.