1. 程式人生 > >AlarmManager定時任務延遲執行

AlarmManager定時任務延遲執行

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

AlarmManager Api文件

Note:Beginning in API 19, the trigger timepassed to this (set) methodis treated as inexact: the alarm will not be delivered before this time, butmay be deferredand 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) andsetExact(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);
    }