Set Repeated alarm at specific time every day

流过昼夜 提交于 2019-11-30 18:12:47

问题


I try to use alarm manager to run alarm at specific time every day. I am using this code

Intent intent = new Intent(AlarmSettings.this, AlarmService.class);
                        intent.putExtra("i", i);
PendingIntent mAlarmSender = PendingIntent.getService(AlarmSettings.this, Id, intent, 0);

AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);

am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),Calendar.getInstance().getTimeInMillis()+(24*60*60*1000), mAlarmSender);}

the problem was in if cal.getTimeInMillis() value is in the past the alarm run immediately, i do not know why, and when cal.getTimeInMillis() value is in the future it runs correctly at its time.

I need to make it run at specific time every day.


回答1:


It looks like your call to

setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation)

Try to set proper triggerAtTime (in the future) - like

Calendar.getInstance().getTimeInMillis()+(24*60*60*1000)

The third param (interval) should obviously be your interval, like

24*60*60*1000



回答2:


// every day at 9 am
Calendar calendar = Calendar.getInstance();

// if it's after or equal 9 am schedule for next day
if (Calendar.getInstance().get(Calendar.HOUR_OF_DAY) >= 9) {
    calendar.add(Calendar.DAY_OF_YEAR, 1); // add, not set!
}
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmManager.setInexactRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pi);

// alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
// AlarmManager.INTERVAL_DAY, pi);



回答3:


This helped me a lot, I had a case where I was using minutes also and came up with the following small amendment:

/* Create calendar and set desired time before this*/

// Compare the current time milliseconds with the desired calendar time milliseconds
if (java.util.Calendar.getInstance().getTimeInMillis() >= 
            calendar.getTimeInMillis() ) {
    calendar.add(Calendar.DAY_OF_YEAR, 1);
}


来源:https://stackoverflow.com/questions/7938957/set-repeated-alarm-at-specific-time-every-day

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