问题
I'm creating an alarm widget, and it works, however, I'm currently using it for a single day, I'd like to know how to define it for predefined days, let's say for example I want to setup the alarman for monday, wednesday and friday, how can I accomplish that?
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, dPicker.getYear());
cal.set(Calendar.MONTH, dPicker.getMonth());
cal.set(Calendar.HOUR_OF_DAY, tPicker.getCurrentHour());
cal.set(Calendar.MINUTE, tPicker.getCurrentMinute());
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmMgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), testThis(this));
I'm currently using a TimePicker and a DatePicker, but I will change the design to use checkboxes, each per day, but I'm not sure how to define the alarm for the selected days, any help? thank you so much.
回答1:
Defining them at once i don't know if this can be achieved, but i have another scenario to use. Say that you adjusted the Alarm to fire on Monday, Tuesday , Thursday. you will adjust the AlarmManager just for Monday and on Monday it should fire and checks for the next alarm ( which will be on Tuesday ) and so on. Save all you alarms in a database and take them out one be one and in each alarm check for the next one ( if exists )
回答2:
You can use the Calendar.DAY_OF_WEEK api like this:
cal1.set(Calendar.DAY_OF_WEEK,2); //monday
cal2.set(Calendar.DAY_OF_WEEK,4); //wednesday
cal3.set(Calendar.DAY_OF_WEEK,6); //friday
and sets 3 alarmMgr like this:
alarmMgr.set(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, testThis(this)); // every monday
alarmMgr.set(AlarmManager.RTC_WAKEUP, cal2.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, testThis(this)); // every wednesday
alarmMgr.set(AlarmManager.RTC_WAKEUP, cal3.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7, testThis(this)); // every friday
来源:https://stackoverflow.com/questions/19297519/how-to-set-an-alarmmanager-for-preselected-days