How to configure the alarm manager for each specific day of the week and time in Android?

For example, I want to have an alarm clock that goes off every Sunday at noon .... how would I do it?

+8
java android alarmmanager
source share
2 answers

Use the AlarmManager class:

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

Class Overview

This class provides access to system alarms. This allows you to plan to launch your application at some point in the future. When an alarm is extinguished, the intent that was registered for it is broadcast by a system that automatically launches the target application if it does not already work. Registered alarms are saved while the device is sleeping (and if desired, can activate the device up if they leave at this time), but will be cleared if it is turned off and rebooted.

Use public void set (int type, long triggerAtTime, PendingIntent operation) to set its start time.

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

Here is a complete example. I really donโ€™t remember all the calendar methods, so Iโ€™m sure that the part can be simplified, but this is the beginning 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); 
+14
source share

finally, this is the right solution, if set to (sun, tus, fri), you must create three alarms in these three days, the following code sets an alarm every Sunday and sends dayOfWeek = 1;

  public void setAlarm_sun(int dayOfWeek) { cal1.set(Calendar.DAY_OF_WEEK, dayOfWeek); Toast.makeText(getApplicationContext(), "sun "+cal1.get(Calendar.DAY_OF_WEEK), 222).show(); Toast.makeText(getApplicationContext(), "Finsh", 222).show(); Intent intent = new Intent(this, SecActivity.class); PendingIntent pendingIntent0 = PendingIntent.getBroadcast(this, 0, intent, 0); PendingIntent pendingIntent = PendingIntent.getActivity(this, 12345, intent, PendingIntent.FLAG_UPDATE_CURRENT); Long alarmTime = cal1.getTimeInMillis(); AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE); // am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime,7* 24 * 60 * 60 * 1000 , pendingIntent); am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime,7* 24 * 60 * 60 * 1000 , pendingIntent); } 
0
source share

All Articles