Steve Steve - 16 days ago 10
Android Question

Set alarm for several days

I'm working on alarm clock app. I've faced with one problem. I do not know how to set alarm for several days. I've already tried the code that is below but in log I saw this

Wed Apr 06
(didn't change any date so it should be nearest tuesday and friday). What do I do wrong? May be I should set alarm separately for every other day?

This is my code:

calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY, Calendar.FRIDAY);
//calendar.add(Calendar.DAY_OF_WEEK,Calendar.FRIDAY);
Log.e("Point_1","Calendar " + calendar.getTime());
calendar.set(Calendar.HOUR_OF_DAY,timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE,timePicker.getCurrentMinute());
Intent intent1 = new Intent(MyService_alarm.this,MyReceiver_Alarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MyService_alarm.this,intent.getIntExtra("Size", 1),intent1,0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 7 * 24 * 3600 * 1000, pendingIntent);


Thank you.

Answer

That is because you are logging the time before setting the hour and minutes from the time picker,

your code si working fine but to display the time that was set to the Alarm in your log you have to move the Log.e to after you set the Calendar to the hour and minute from your picker so your code should look like this :

calendar.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY, Calendar.FRIDAY);
            //calendar.add(Calendar.DAY_OF_WEEK,Calendar.FRIDAY);
            calendar.set(Calendar.HOUR_OF_DAY,timePicker.getCurrentHour());
            calendar.set(Calendar.MINUTE,timePicker.getCurrentMinute());
            Log.e("Point_1","Calendar " + calendar.getTime());
            Intent intent1 = new Intent(MyService_alarm.this,MyReceiver_Alarm.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(MyService_alarm.this,intent.getIntExtra("Size", 1),intent1,0);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 7 * 24 * 3600 * 1000, pendingIntent);

Also since you are making an Alarm for several days it would be wise to save all the set alarms and to add a receiver to detect when the device has been booted since your alarms are cancelled on reboot and will need to be added again.

Comments