简体   繁体   中英

Alarm manager set alarm on a day of week

I have a time picker dialog where i am picking the time for the alarm. I am then setting what day i want the alarm to go off. If i specify today(saturday) "for day of week" the alarm goes off on the correct time specified on the time picker. If I set lets say monday the alarm goes off instantly as soon as i set it.

How, can i schedule an alarm to go off on a certain day of the week thats not today?

JAVA

timepickerdialog = new TimePickerDialog(AddAlarmActivity.this,
                        new TimePickerDialog.OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay,
                                                  int minute) {

                                Calendar ca = Calendar.getInstance();
                                ca.set(Calendar.HOUR_OF_DAY,hourOfDay);
                                ca.set(Calendar.MINUTE,minute);
                                ca.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
                                ca.set(Calendar.SECOND, 0);
                                ca.set(Calendar.MILLISECOND, 0);

                                AlarmManager alarmManager;
                                alarmManager = (AlarmManager) AddAlarmActivity.this.getSystemService(ALARM_SERVICE);
                                Intent intent;

                                intent = new Intent(AddAlarmActivity.this, AlarmReceiver.class);
                                pendingIntent = PendingIntent.getBroadcast(AddAlarmActivity.this, 0, intent, 0);
                                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, ca.getTimeInMillis(), 1000*60*60*24, pendingIntent);

It appears that if i set the day thats today or none at all it works great. Why wont it work for a day thats not the current day and how can i get it to work? I am turning to SO because im not getting any help with google.

I have also tried ca.set(Calendar.DAY_OF_WEEK, 2);

Thank you

The problem is that your calendar has the date for the alarm set by default to today and the time specified is less than the time when you executing the alarm. The time has already passed and it is informing you even though it is late. Example you run your code at 7:00PM, but the time of the calendar is set to 6:50PM. If you want the alarm to be triggered starting tomorrow then add this to your calendar configuration:

calendar.add(Calendar. DATE, 1);

Also make sure you define your broadcastreceiver on your manifest so the alarm works when the app is not running.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM