我的 AlarmManager 立即触发警报 [英] My AlarmManager fires the alarm immediately

查看:65
本文介绍了我的 AlarmManager 立即触发警报的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然这个问题在 SO 上一遍又一遍地重复,但没有一个解决方案有效,在下面的代码中,它应该在启动我的活动 10 秒后第一次触发,但它会立即启动.而且我正在使用 FLAG_UPDATE_CURRENT 所以没有过去的时间可以立即触发,因为我没有将它设置在特定的小时/分钟/秒.你能不能让我注意我遗漏的东西.

Though this question is repeated over and over here on SO, but non of the solutions are working, in the code below it should fire for the first time after 10 seconds from launching my activity, but it launch immediately. And I'm using FLAG_UPDATE_CURRENT so there's no past time to fire immediately as I'm not setting it at specific hour/minute/sec. Could you please bring my attention to what I'm missing.

我正在 Android 5.0 Targeting API 4.0+ 上进行测试

I'm testing on Android 5.0 Targeting API 4.0+

  • compileSdkVersion 23
  • minSdkVersion 16
  • targetSdkVersion 23

  • compileSdkVersion 23
  • minSdkVersion 16
  • targetSdkVersion 23

Intent myIntent = new Intent(this, check.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

am.setRepeating(AlarmManager.RTC, 10000, (AlarmManager.INTERVAL_DAY/8), pi);

am.setRepeating(AlarmManager.RTC, 10000, (AlarmManager.INTERVAL_DAY / 8), pi);

这是我在 AndroidManifest.xml 中的 check.class

    <receiver
        android:name=".Check"
        android:exported="false" />

推荐答案

10000 实时时钟总是过去的,所以你的闹钟会立即触发.您希望 System.currentTimeMillis() + 10000 作为 setRepeating() 调用中的第二个参数.

10000 on the real time clock is always going to be in the past, so your alarm fires immediately. You want System.currentTimeMillis() + 10000 as the second argument in the setRepeating() call.

我要指出 setRepeating() 在 KitKat 中是不准确的,因此警报触发的实际时间可能已关闭.如果重要,请改用 setExact() 方法,每次触发时在所需的时间间隔内再次设置警报.

I would point out that setRepeating() is inexact as of KitKat, so the actual time the alarm fires may be off. If it matters, use the setExact() method instead, setting the alarm again for the desired interval each time it fires.

这篇关于我的 AlarmManager 立即触发警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆