简体   繁体   English

每天在特定时间设置重复警报

[英]Set Repeated alarm at specific time every day

I try to use alarm manager to run alarm at specific time every day. 我尝试使用警报管理器在每天的特定时间运行警报。 I am using this code 我正在使用此代码

Intent intent = new Intent(AlarmSettings.this, AlarmService.class);
                        intent.putExtra("i", i);
PendingIntent mAlarmSender = PendingIntent.getService(AlarmSettings.this, Id, intent, 0);

AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);

am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),Calendar.getInstance().getTimeInMillis()+(24*60*60*1000), mAlarmSender);}

the problem was in if cal.getTimeInMillis() value is in the past the alarm run immediately, i do not know why, and when cal.getTimeInMillis() value is in the future it runs correctly at its time. 问题是,如果cal.getTimeInMillis()值在过去警报立即运行,我不知道为什么,并且当cal.getTimeInMillis()值在将来它正在运行时。

I need to make it run at specific time every day. 我需要让它在每天的特定时间运行。

// every day at 9 am
Calendar calendar = Calendar.getInstance();

// if it's after or equal 9 am schedule for next day
if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 9) {
    calendar.add(Calendar.DAY_OF_YEAR, 1); // add, not set!
}
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pi);

// alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
// AlarmManager.INTERVAL_DAY, pi);

It looks like your call to 它看起来像你的电话

setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)

Try to set proper triggerAtTime (in the future) - like 尝试设置正确的triggerAtTime(将来) - 就像

Calendar.getInstance().getTimeInMillis()+(24*60*60*1000)

The third param (interval) should obviously be your interval, like 第三个参数(间隔)显然应该是你的间隔,就像

24*60*60*1000

This helped me a lot, I had a case where I was using minutes also and came up with the following small amendment: 这对我帮助很大,我有一个案例,我也在使用分钟,并提出了以下小修正案:

/* Create calendar and set desired time before this*/

// Compare the current time milliseconds with the desired calendar time milliseconds
if (java.util.Calendar.getInstance().getTimeInMillis() >= 
            calendar.getTimeInMillis() ) {
    calendar.add(Calendar.DAY_OF_YEAR, 1);
}

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

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