为什么AlarmManager.setRepeating中的triggerAtTime不起作用

Ric*_* Li 3 android

AlarmManager mgr=
      (AlarmManager)ctxt.getSystemService(Context.ALARM_SERVICE);
  Intent i=new Intent(ctxt, AlarmReceiver.class);
  PendingIntent pi=PendingIntent.getBroadcast(ctxt, 0, i, 0);
mgr.setRepeating(
  AlarmManager.ELAPSED_REALTIME_WAKEUP,
  System.currentTimeMillis() + 1000,
  1000, pi);
Run Code Online (Sandbox Code Playgroud)

根据android doc

triggerAtMill使用适当的时钟(取决于警报类型),警报首先应该以毫秒为单位的时间.

该动作应该在1秒后开始,但它永远不会被调用,为什么?

Luc*_*fer 8

而不是AlarmManager.ELAPSED_REALTIME_WAKEUP在setRepeating()方法中,使用AlarmManager.RTC_WAKEUP如下所示,

mgr.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + 1000, 1000, pi);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,再次检查了AlarmManager文档.它取决于类型,使用RTC_WAKEUP,System.currentTimeMillis(); ELAPSED_REALTIME_WAKEUP需要相应的SystemClock.elapsedRealtime() (2认同)

Ric*_* Li 5

我谷歌了很多,但似乎没有人遇到同样的问题。最后我发现我应该使用 SystemClock.elapsedRealtime() 代替。

对于 triggerAtMillis,因为类型是 AlarmManager.ELAPSED_REALTIME_WAKEUP SystemClock.elapsedRealtime() 应该使用而不是 System.currentTimeMillis()

问题已解决。