AlarmManager.setRepeating将不再准确

Android定时任务变动
从API19开始,Android系统的AlarmManager不再确保定时任务精确执行。为节省电量,系统可能延迟执行定时任务。本文介绍变动原因及如何使用setWindow或setExact方法解决。
背景:
当我们想让Android应用程序定时为做一件工作时,我们往往会在一个BroadcastReceiver中使用AlarmManager.setRepeating()方法来实现。在API 19(即Kitkat)之后,这一方法将不再准确地保证每次工作都在你设置的时间开始。

解释:

Note: Beginning in API 19, the trigger time passed to this 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 requesteddelivery 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).

原来,操作系统为了节能省电,将会调整alarm唤醒的时间。故通过AlarmManager.setRepeating()方法将不再保证你定义的工作能按时开始。


解决办法:

1. 按照官方网站说的,调用API 19之后出现的setWindow()或者setExact()方法。

2. 按照如下方法写scheduleAlarm()方法:

public class PollReceiver extends BroadcastReceiver {
   private static final int PERIOD = 60000// 1 minutes

   @Override
   public void onReceive(Context ctxt, Intent i{
       if (i.getAction().equals("great")) {
           scheduleAlarms(ctxt);
             //Do your work
       }
   }

   static void scheduleAlarms(Context ctxt{
       AlarmManager mgr = (AlarmManagerctxt.getSystemService(Context.ALARM_SERVICE);
       Intent i = new Intent(ctxt, PollReceiver.class);
       i.setAction("great");
       PendingIntent pi = PendingIntent.getBroadcast(ctxt, 0, i, 0);.
       mgr.cancel(pi);
       mgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime()+PERIOD, pi);

   }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值