Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i set an alarm manager to fire every on specific day of week and time in android?

for example i want to have an alarm that will fire every sunday at noon.... how would i do this?

like image 650
waa1990 Avatar asked Apr 08 '11 23:04

waa1990


1 Answers

Use the AlarmManager class:

http://developer.android.com/reference/android/app/AlarmManager.html

Class Overview

This class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. Registered alarms are retained while the device is asleep (and can optionally wake the device up if they go off during that time), but will be cleared if it is turned off and rebooted.

Use public void set (int type, long triggerAtTime, PendingIntent operation) to set the time to fire it.

Use void setRepeating(int type, long triggerAtTime, long interval, PendingIntent operation) to schedule a repeating alarm.

Here's a full example. I don't really remember all the Calendar methods, so I'm sure that part can be streamlined, but this is a start and you can optimize it later:

AlarmManager alarm = (AlarmMAnager) Context.getSystemService(Context.ALARM_SERVICE);
Calendar timeOff = Calendar.getInstance();
int days = Calendar.SUNDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)); // how many days until Sunday
timeOff.add(Calendar.DATE, days);
timeOff.set(Calendar.HOUR, 12);
timeOff.set(Calendar.MINUTE, 0);
timeOff.set(Calendar.SECOND, 0);

alarm.set(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), yourOperation);
like image 198
Aleadam Avatar answered Oct 10 '22 12:10

Aleadam