Android. Alarm Manager fires in strange times

ε祈祈猫儿з 提交于 2019-12-04 02:35:38

From the API (here):

Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.

So, if you are using API 19, then answers to your two questions...

How can I enforce the system to run exactly every 5 minutes (or to try harder)?

Try this code, it works 100%

Calendar calendar = new GregorianCalendar();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(System.currentTimeMillis());


calendar.set( Calendar.MINUTE, 00 );
calendar.set( Calendar.SECOND, 00 );

Intent intent = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0 );
hourlyAlarm = (AlarmManager) context.getSystemService( Context.ALARM_SERVICE );
hourlyAlarm.setRepeating( AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),1000 * 60 * 5, pi );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!