How to set an AlarmManager for preselected days?

谁说胖子不能爱 提交于 2019-12-11 19:46:27

问题


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

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