Android AlarmManager fire at wrong time

孤街浪徒 提交于 2019-12-02 22:31:01

问题


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

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. Is there something missing in my code that result in firing the alarm at a wrong time?


回答1:


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.



来源:https://stackoverflow.com/questions/28037173/android-alarmmanager-fire-at-wrong-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!