简体   繁体   English

Android AlarmManager在错误的时间触发

[英]Android AlarmManager fire at wrong time

My app will set an AlarmManager to fire some event and repeat it on 12:00pm everyday. 我的应用程序将设置一个AlarmManager来触发某些事件,并在每天的12:00 pm重复一次。 However, my clients report that the alarm sometimes wake up normally, but sometimes wake up at other time (eg. 10/11pm). 但是,我的客户报告说,警报有时会正常唤醒,但有时会在其他时间(例如10 / 11pm)唤醒。

Here is the code snippet: 这是代码片段:

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);

For cancelling the alarm: 取消警报:

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);

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. 因此,我使用FLAG_UPDATE_CURRENT来确保在特定时间仅执行一项任务。 Is there something missing in my code that result in firing the alarm at a wrong time? 我的代码中是否缺少什么导致在错误的时间触发警报?

I think you could do this in simpler way like below: 我认为您可以通过以下更简单的方式执行此操作:

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.

Hope this helps. 希望这可以帮助。

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

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