计算Android警报的时间
在安卓系统中,我们通过设置警报发出的时间(以毫秒为单位)来设置警报。有没有一种简单的方法来计算到某个特定时间(hh:mm)还有多少毫秒,或者我只需要用数学方法来计算它 谢谢 现在日期=新日期(),b=新日期(年、月、日、小时、分钟) b、 getTime()-a.getTime()计算Android警报的时间,android,alarm,Android,Alarm,在安卓系统中,我们通过设置警报发出的时间(以毫秒为单位)来设置警报。有没有一种简单的方法来计算到某个特定时间(hh:mm)还有多少毫秒,或者我只需要用数学方法来计算它 谢谢 现在日期=新日期(),b=新日期(年、月、日、小时、分钟) b、 getTime()-a.getTime() 请查看的第一个参数:使用RTC/RTC_WAKEUP,可以指定固定时间而不是经过的时间 也就是说,如果您需要使用经过的时间,那么计算需要经过的毫秒数是非常简单的。最糟糕的情况是,您可以使用日历和/或日期类。将当前时间
请查看的第一个参数:使用RTC/RTC_WAKEUP,可以指定固定时间而不是经过的时间
也就是说,如果您需要使用经过的时间,那么计算需要经过的毫秒数是非常简单的。最糟糕的情况是,您可以使用
日历
和/或日期
类。将当前时间(以毫秒为单位)保存为
Calandar calendar = Calendar.getInstance();
Long currenttime = calendar.getTimeInMillis();
Long settime= <your set time in milliseconds>;
您可以在此处设置日历中的时间:
calendar.set(Calendar.SECOND, calendar.get(Calendar.SECOND) + dif);
在这里,您可以设置设置时间的警报
AlarmManager alarmManager1 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager1.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi1);
这里还有另一种方法,以毫秒为单位计算某个时间:
Calendar c = Calendar.getInstance();
c.set(c.YEAR, c.MONTH, c.DAY_OF_MONTH, 17, 1, 0); // 5:01 pm
long alarmTime = c.getTimeInMillis();
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmNotification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 1000 * 60 * 60 * 24, pendingIntent); // Millisec * Second * Minute * Hour // Same time every day
- RTC_WAKEUP允许闹钟在手机处于睡眠状态时仍然激活。如果要等待用户自己唤醒手机,请使用RTC
- 如果不希望警报重复,请使用am.set()
如果有帮助,请告诉我。所谓的“固定时间”是指实际上可以用HH:mm格式键入它吗?是的。您可以将其指定为Unix时间戳(您可以使用类似于
Date
)的内容来创建它。我们如何将其输入set()?同样,请参阅文档。使用RTC/RTC_WAKEUP作为参数,第二个参数triggerAtTime
是以毫秒为单位的UNIX时间戳。例如,您可以使用Date.getTime()
来获得它。啊,我明白了,从纪元开始已经是秒了?
Calendar c = Calendar.getInstance();
c.set(c.YEAR, c.MONTH, c.DAY_OF_MONTH, 17, 1, 0); // 5:01 pm
long alarmTime = c.getTimeInMillis();
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmNotification.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 1000 * 60 * 60 * 24, pendingIntent); // Millisec * Second * Minute * Hour // Same time every day