简体   繁体   中英

Android - Alarms sometimes fires at the wrong time using AlarmManager

This problem seems a little bit odd, but if someone as encounter something like this, please help me...

I created an Alarm Scheduler, that sends an alarm to the user using AlarmManager , through this code:

    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra("tk_alert_id", lastAlertId.getId()+"");
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, idRandom, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTimeInMillis(), pendingIntent);

The problem is that, sometimes, I receive this alarm on my AlarmReceiver ( BroadcastReceiver ) at a wrong time, as you can see in the image bellow: image , and I can't figure out what's the problem... I checked the time for date and was set as "2015-05-27 17:00:00", but it was received a little minutes earlier (around 16:57) ...

Does anyone knows what kind of problem I am encountering here?

For API levels <19 you should use AlarmManager.setRepeating() and your alarms will trigger exactly at specified time.

Api levels >=19 and above this no longer works. There was change in android so that all repeating alarms are inexact.

So if you would like to achieve exact repeating alarm use AlarmManager.setExact().

See this question for more info.

Edit For your purpose (a one-off alarm, at a precise time) use alarmManager.setExact(....). See docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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