Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set time for alarm for next day in Android app?

Tags:

android

I am creating an Android application, and I have a problem.(I am new to Android development)

In my application, I want to set alarm for today. It works for that, but my problem is when I want to set time from time picker as less than the current time, my alarm rings immediately. I want to set that time for tomorrow's time. How do I do that?

like image 376
user903704 Avatar asked Dec 04 '22 07:12

user903704


1 Answers

Simply check the results of the time picker before setting the alarm. I'm not sure exactly how your setting your alarm, or what kind of alarm your even using, I will assume that given a time in millis you can work it out.

public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
    Calendar now = Calendar.getInstance();
    Calendar alarm = Calendar.getInstance();
    alarm.set(Calendar.HOUR_OF_DAY, hourOfDay);
    alarm.set(Calendar.MINUTE, minute);
    long alarmMillis = alarm.getTimeInMillis();
    if (alarm.before(now)) alarmMillis+= 86400000L;  //Add 1 day if time selected before now
    setAlarm(alarmMillis);
}

public void setAlarm(long millis) { 
    /** Set your alarm here */
}

There are many other ways to do this, but I find the Calendar class is usually good for time manipulation for beginners. Hope this helps.

EDIT: If DST is a concern, a small edit will solve the problem:

public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
    Calendar now = Calendar.getInstance();
    Calendar alarm = Calendar.getInstance();
    alarm.set(Calendar.HOUR_OF_DAY, hourOfDay);
    alarm.set(Calendar.MINUTE, minute);
    if (alarm.before(now)) alarm.add(Calendar.DAY_OF_MONTH, 1);  //Add 1 day if time selected before now
    setAlarm(alarm.getTimeInMillis());
}

You will need to make sure the Time Zone is correctly set. The above code will use the Default Time Zone which is set by the System based on your Android Locale settings. Use Calendar.getInstance(TimeZone zone) to get the Calendar object in a specific Time Zone.

like image 87
Chris Noldus Avatar answered Dec 05 '22 20:12

Chris Noldus