Android repeat alarm manager in not triggering immediately

非 Y 不嫁゛ 提交于 2019-12-06 17:26:39

You should change your code to :

PendingIntent pi=PendingIntent.getBroadcast(context,0,myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
      alarmManager.setExact(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pi);
} else {
      alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pi);
}

@Edit Above code will work for set exactly time. But this section will explain about repeating for alarm manager.

For api below 19, we use AlarmManager.setRepeating() will make alarms trigger exactly at specified time periodically. But from 19 and newer, this method won't work again and there aren't any apis support this behavior. I think this api change make developers thinking more carefully when they create a timer. Because a timer trigger at exactly time periodically will drain battery so much.

If you want you must do on your own. Firstly, you set AlarmManager.setExact() and when alarm trigger, you will make alarm trigger again next time manually

Here is the code:

PendingIntent pi=PendingIntent.getBroadcast(context,0,myIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
     alarmManager. setExact(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pi);
} else {
     alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pi);
}

And in your intent, where you put handle code, you should check if android api >= 19, application will create new alarm for the next event.

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
         doSomething();
         // calculate time for next event
         Calendar nextEvent = calcNextEvent();
         // and set alarm again
         alarmManager. setExact(AlarmManager.RTC_WAKEUP, nextEvent.getTimeInMillis(), pi);
 } else {
         doSomething();
 }

I think this is problem in android api design. Old code should work on newer version. Anyway, this new api design make everything clearer for developer, better for system(save battery). Of course, when you use new api :)

Hope this help :)

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