Android AlarmManager在错误的时间触发 [英] Android AlarmManager fire at wrong time
问题描述
我的应用程序将设置AlarmManager触发某些事件,并在每天的12:00 pm重复该事件。
但是,我的客户报告说,警报有时会正常唤醒,但有时会在其他时间唤醒(例如10 / 11pm)。
My app will set an AlarmManager to fire some event and repeat it on 12:00pm everyday. However, my clients report that the alarm sometimes wake up normally, but sometimes wake up at other time (eg. 10/11pm).
代码段:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
if (calendar.get(Calendar.HOUR_OF_DAY) >= 12 && calendar.get(Calendar.MINUTE) > 0) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.PM);
int interval = (60 * 60 * 24 * 1000);
Intent intent = new Intent(mContext, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, AlarmReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval, pendingIntent);
要取消警报:
Intent intent = new Intent(mContext, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, AlarmReceiver.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
启动应用程序/在一项活动中启用此设置时,我的应用程序将启动警报。因此,我使用FLAG_UPDATE_CURRENT来确保在特定时间仅执行一项任务。我的代码中是否缺少某些内容,导致在错误的时间触发了警报?
My app will start the alarm when the app is launch/turn on this setting in one of the activity. Therefore I use the FLAG_UPDATE_CURRENT to ensure only one task will fire at the specific time. Is there something missing in my code that result in firing the alarm at a wrong time?
推荐答案
我认为您可以在
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 12); // 12 PM
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
60 * 60 * 24 * 1000, pendingIntent); // Daily interval, setting RTC_WAKEUP does exact time and forces device to wake up.
希望这会有所帮助。
这篇关于Android AlarmManager在错误的时间触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!