AlarmManager定时任务延迟执行

原文地址:http://blog.csdn.net/pashanhuxp/article/details/47154361


AlarmManager Api文档

Note:   Beginning in API 19, the trigger time  passed to this ( set) method  is treated as inexact: the alarm will not be delivered before this time, but  may be deferred and delivered some time later. The OS will use this policy in order to "batch" alarms together across the entire system, minimizing the number of times the device needs to "wake up" and minimizing battery use. In general, alarms scheduled in the near future will not be deferred as long as alarms scheduled far in the future.
 
With the new batching policy, delivery ordering guarantees are not as strong as they were previously. If the application sets multiple alarms, it is possible that these alarms' actual delivery ordering may not match the order of their requested delivery times.   If your application has strong ordering requirements there are other APIs that you can use  to get the necessary behavior; see setWindow(int, long, long, PendingIntent) and   setExact(int, long, PendingIntent).
 
Applications whose targetSdkVersion is before API 19 will continue to get the previous alarm behavior: all of their scheduled alarms will be treated as exact.

意思就是说,自Api19开始,set方法设置的闹钟可能会发生deferred(延迟),因为OS基于尽可能减少设备唤醒和电池损耗考虑,所以OS不推荐设置过多的闹钟。如果实在需要闹钟准时响应,可以采用setExact方法。

修改成如下解决:

    int apiLevel = Build.VERSION.SDK_INT;

    PendingIntent pendingIntent = setPendingIntent(mContext, note);

    long triggerAtMillis = getTriggerTime(note);

    AlarmManager alarm = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);

    if (apiLevel >= 19) {
      Log.d(TAG, "alarm.set Exact!");
      alarm.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
    } else {
      Log.d(TAG, "alarm.set only");
      alarm.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值