简体   繁体   中英

Android - how to set alarm X days before specific date

I have seen a lot of tutorials for creating an AlarmManager and bringing up a notification at a specific date, but I was wondering how to do it for X days before.

For example, if I have an event on January 8th, 2014 and I want to set it a week before to Jan 1st, 2014, I would just set the alarm as this:

Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.MONTH, 1);
calendar.set(Calendar.YEAR, 2013);
calendar.set(Calendar.DAY_OF_MONTH, Day-7);

calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM,Calendar.AM);

Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

However what if the event was on January 4th, 2014, then I would want to set the date to December 28th, 2013. Is there a function that can do this? Or do I have to write a lot of cases?

the event was on January 4th, 2014:

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.YEAR, 2014);
calendar.set(Calendar.DAY_OF_MONTH, 4);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
long eventTime=calendar.getTimeInMillis();//Returns Time in milliseconds

long oneDay=AlarmManager.INTERVAL_DAY;//Converts 24 Hrs(1 Day) to milliseconds
int noOfDays=4
long reminderTime=eventTime-(noOfDays*oneDay);//Time in milliseconds when the alarm will shoot up & you do not need to concider month/year with this approach as time is already in milliseconds.

//Set alarm
Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, reminderTime, pendingIntent);

Hope this helps!

get your current time in milliseconds and subtract the no. of days from it,here 1 day= 24*60*60*1000 = 86400000

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
  alarmManager.set(AlarmManager.RTC_WAKEUP, (calendar.getTimeInMillis()-(no. of days * 86400000)), pendingIntent);

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