AlarmManager Interval for Android

2019-05-17 20:52发布

This is the code I have so far

AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
setRepeatingAlarm();

public void setRepeatingAlarm() {

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 10);

    Intent intent = new Intent(this, TimeAlarm.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), (15 * 1000), pendingIntent);
  }

}

This is all I am trying to accomplish: The alarm will not turn on until 30 seconds past every minute. Once you clear it, it wont comes back on until 30 seconds past the next minute. So if I open the app, and it is 25 second past the minute, it will activate status bar notification 5 second later. But if it is 40 seconds past, I will have to wait 50 more seconds (into the next minute). I am not sure how to use the Calendar function to attain this?

2条回答
何必那么认真
2楼-- · 2019-05-17 21:32

If you check the documentation for AlarmManager, it says that RTC_WAKEUP use time relative to System.currentTimeMillis():

RTC_WAKEUP Alarm time in System.currentTimeMillis() (wall clock time in UTC), which will wake up the device when it goes off.

So simply modify your triggerAtTime parameter, for instance to start right away:

am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 15 * 1000, pendingIntent);

Then the alarm will be repeatedly fire every 15 seconds.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-05-17 21:48

If I understand your requirement then you could try something like the following...

Calendar cal = Calendar.getInstance();
if (cal.get(Calendar.SECOND) >= 30)
    cal.add(Calendar.MINUTE, 1);
cal.set(Calendar.SECOND, 30);

// Do the Intent and PendingIntent stuff

am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60 * 1000, pendingIntent);
查看更多
登录 后发表回答