我正在制作一个简单的闹钟应用程序,模仿Android Lollipop附带的默认闹钟应用程序。
set*( )
的{{1}}方法需要将警报作为Unix纪元发布的日期。
使用AlarmManager
,用户界面相当简单。
因此,考虑到用户从TimePicker
中选择的当前时间和时间,我如何计算应该触发警报的时间(以毫秒为单位)?
更新
我遇到两种情况:
选择当前时间之后的时间:
假设是上午11点,用户从时间选择器中选择时间为03pm。在这种情况下,我知道警报应安排在同一天。
选择当前时间之前的时间:
假设是上午11点,用户从时间选择器中选择时间为上午10点。在这种情况下,我知道警报应安排在第二天的上午10点。
答案 0 :(得分:2)
好的,你走了:
// Get the current time
final Date currentTime = new Date();
// Set the hours and minutes from the time picker against todays date
final Calendar selectedTime = Calendar.getInstance();
selectedTime.set(Calendar.HOUR_OF_DAY, hourFromTimePicker);
selectedTime.set(Calendar.MINUTE, minuteFromTimePicker);
// If the current date is greater than the hour and minute from time picker add one day
if (currentTime.getTime() > selectedTime.getTime().getTime()) {
selectedTime.add(Calendar.DAY_OF_YEAR, 1);
}
// Schedule the alarm
//AlarmManager.set(selectedTime.getTime().getTime());
答案 1 :(得分:0)
我会使用android.text.format.Time
类
调用Time类的setter来设置Hour,Minute,Second等。小时是24小时,所以如果current hour > selected hour
那么你知道将days
增加1
最后,致电Time#toMillis(boolean ignoreDst)
以毫秒获取系统时间,并将其传递给AlarmManager
编辑:应该使用GregorianCalendar。
答案 2 :(得分:0)
如果您在java Date对象中存储数据:
long getTime( )
返回自1970年1月1日以来经过的毫秒数。只需减去。
另一种方式,如果你只在一天内看时间:
int ms = 1000*SECONDS + 1000*60*MINUTES + 1000*60*60*HOURS