Search code examples
androidsdkcalendaralarmmanager

Repeat scheduled tasks on selected days in Android sdk alarm manager


I have tried to do this without bothering the experts and have read numerous threads here and on other sites. It is clearly my brain not understanding what needs to be done in order for this to work.

My goal is that the app allows the user to enter a time and one or more days in a week. All of the GUI side and storing of the dates and times I have done, however to get the alarm manager to repeat, lets say every Monday at 14:00 and then can send at 14:02 . I have used the java Calendar object to hold the times and days of the week or even used date and day of the week of the month. These are then , as needed, converted to milliseconds for it to be read in by the alarm manager.

I then have used either the alarm manager set or set repeat methods to repeat the event. All I am able to do is get it to occur once and then if I change the emulator date and time to another Monday nothing happens.

The GUI holds the hours and minutes in required variables and then these are used against the calendar objects.

The alarm manager calls a broadcast receiver for the event to occur.

Please can someone simply give an example on how to set specific days such as Monday , Wednesday Friday. I know that separate alarm managers are needed for each day and at the moment I have just focused on Monday as my main test.

Links viewed:


Managed to figure this out now and so follows my answer:

The following code calculates the remaining days between now and the day needed for the scheduled task. the variable whichday is passed via parameter from the method this code belongs to. In the understanding of this whichday represents days of the week 1 through to 7 where 1 is Sunday , 2 is Monday and so .

//This gets the current day of the week as of TODAY / NOW
int checkcurrentday = getcurtime.get(Calendar.DAY_OF_WEEK);

// This calculates the days between now and the day needed which is represented by whichday.
int numberofdays = Calendar.SATURDAY + whichday - checkcurrentday;

//Now add NOT set the difference of the days to your Calendar object
tMondayOn.add(Calendar.DATE, numberofdays);

Solution

  • Well, you need to first use the Java Calendar API (or Joda!) to figure out when the next monday is. Set the alarm to to that time in milliseconds then use setRepeating and pass in a long that represents the interval of one week.