AlarmManager Interval for Android

雨燕双飞 提交于 2019-12-22 10:26:35

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/10905391/alarmmanager-interval-for-android

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