开发者

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

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?


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.


Here is the code I used in my project. I get instance of calendar, then set required time and compare it to actual time value, if its less than zero (past) I add one day to it. Hope it helps.

Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, hour);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, second);
    long timeInMillis = c.getTimeInMillis();
    if(timeInMillis-System.currentTimeMillis()<0){
        //if its in past, add one day
        timeInMillis += 86400000;
    }
    //for instance start repeating intent
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, AlarmManager.INTERVAL_DAY, pendingIntent);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜