How to set the time for the alarm clock of the next day in the android app?

I'm creating an Android application and I have a problem. (I'm a novice in Android Development)

In my application, I want to set the alarm clock for today. It applies to this, but my problem is that when I want to set the time from the time selector to be less than the current time, my alarm rings immediately. I want to set the time for tomorrow. What do I do?

resolvent:

Before setting the alarm, just check the result of the time selector. I'm not sure how you set your alarm clock, or even what kind of alarm clock you use, I'll assume you can solve it in milliseconds

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 that the calendar class is usually suitable for beginners' time operation. I hope this can help

Edit: if DST is a problem, 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 need to ensure that the time zone is set correctly. The above code will use the default time zone set by the system according to your Android regional settings. Use calendar.getinstance (timezone area) to obtain the calendar object in a specific time zone

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>