简体   繁体   English

AlarmManager立即触发警报

[英]AlarmManager firing Alarm Instantly

Intent myIntent = new Intent(Alarm.this, Automaton.class);
                  myIntent.putExtra("methodName", "myMethod");
                  myIntent.putExtra("hour", tp.getCurrentHour().toString());
                  myIntent.putExtra("minute", tp.getCurrentMinute().toString());
                  hour = tp.getCurrentHour();
                  minute = tp.getCurrentMinute();
                  PendingIntent pendingIntent = PendingIntent.getActivity(Alarm.this, 0, myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
                  AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
                       Calendar calendar = Calendar.getInstance();
                       calendar.set(calendar.HOUR_OF_DAY, hour);
                       calendar.set(calendar.MINUTE, minute);
                       calendar.set(calendar.SECOND, 0); 
                       alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 86400000, pendingIntent);

Above is my code. 以上是我的代码。 Here is my problem; 这是我的问题; I have a method in another Activity that I want to run at a specified time. 我在另一个Activity中有一个方法,我希望在指定的时间运行。 If the user selects a time that HASN'T passed yet in the day (say you set the alarm at 10AM for 11AM, it will work fine). 如果用户选择当天尚未通过的时间(例如,您在上午10点将警报设置为上午11点,它将正常工作)。 However, if you set the alarm for 9AM at 10AM, it will instantly fire the Pending Intent. 但是,如果您在上午10点将警报设置为9AM,它将立即触发Pending Intent。 Not sure where I am going wrong. 不知道我哪里错了。 Any help would be appreciated! 任何帮助,将不胜感激!

You might need to check whether the set time is less than the current time . 您可能需要检查set time是否小于current time If the set time is less than current time, don't set an alarm for it. 如果设定时间小于当前时间,请勿为其设置警报。 Because it's useless even if you keep it when the time has already passed. 因为即使你已经过了时间就保持它也没用。

您可以使用日历实例并将日期设置为第二天,并将其与警报一起使用。

To what @shreyas said, you need to do the check yourself if you need to bump the day. 对于@shreyas所说的,如果你需要碰一天,你需要自己检查一下。

Example.. If they select 5:00PM (HOUR_OF_DAY = 17) compare that to current time. 示例..如果他们选择下午5:00(HOUR_OF_DAY = 17)将其与当前时间进行比较。 If that time (17) is less that the current time, then add a day to your calendar instance. 如果该时间(17)小于当前时间,则向您的日历实例添加一天。

 int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); calendar.set(calendar.DAY_OF_WEEK, dayOfWeek + 1); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM