Search code examples
androidservicealarmmanagerrepeatingalarm

Upcoming alarm triggers immediately


I have used AlarmManager to set the alarm and passed the time from timePicker.

I want to set alarm at the given time but if the time(that I am going to set) has been passed then the alarm triggers immediately .

Example:- If the current time is 9:00 PM and I set alarm for 7:00PM then the alarm triggers immediately.

Below is my code

public void startAlarm(Calendar c, int id){
    Toast.makeText(this, "Alarm in on", Toast.LENGTH_SHORT).show();
    Intent intent = new Intent(this,AlarmReciever.class);
    intent.putExtra("id",id);

    //int _id = (int)System.currentTimeMillis();

    PendingIntent pendingIntent = PendingIntent.getBroadcast(this,id,intent,PendingIntent.FLAG_ONE_SHOT);
    alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(), 1000*60,pendingIntent);
    //alarmManager.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
}

How to control the triggering of alarm if the time for which we are setting alarm has been passed?


Solution

  • You will need to detect if the calendar time is in the past and adjust it accordingly. Like so:

    public void startAlarm(Calendar c, int id){
        Toast.makeText(this, "Alarm in on", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(this,AlarmReciever.class);
        intent.putExtra("id",id);
    
        //Check if calendar is set in the past
        if (c.getTimeInMillis() < System.currentTimeMillis()) {
            //Add one day to the calendar (or whatever repeat interval you would like)
            c.add(Calendar.DAY_OF_YEAR, 1);
        }
    
        //int _id = (int)System.currentTimeMillis();
    
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this,id,intent,PendingIntent.FLAG_ONE_SHOT);
        alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(), 1000*60,pendingIntent);
        //alarmManager.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
    }
    

    As I'm not sure how you are allowing the user to set the time I'm not sure if the addition of one day will always do the trick. For instance, if you allow the user to pick a date from a calendar it may be years in the past. You will need to adjust how much time you add based on your desired repeat interval and how you are allowing the user to set the time.