My AlarmManager fires the alarm immediately

折月煮酒 提交于 2021-02-08 12:13:50

问题


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.

I'm testing on Android 5.0 Targeting API 4.0+

  • 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);

And this is my check.class in AndroidManifest.xml

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

回答1:


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.

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.



来源:https://stackoverflow.com/questions/36675477/my-alarmmanager-fires-the-alarm-immediately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!