Android - 如何在特定日期之前设置警报X天

时间:2014-04-08 05:59:41

标签: android calendar notifications alarmmanager

我已经看过很多关于创建AlarmManager并在特定日期发布通知的教程,但我想知道如何在X天之前完成它。

例如,如果我在2014年1月8日举办了一个活动,并且我想在2014年1月1日前一周设置它,我只需将闹钟设置为:

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);

然而,如果活动是在2014年1月4日,那么我想将日期设置为2013年12月28日。是否有可以执行此操作的功能?或者我必须写很多案例?

2 个答案:

答案 0 :(得分:2)

该活动于2014年1月4日举行:

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);

希望这有帮助!

答案 1 :(得分:1)

以毫秒为单位获取当前时间并减去no。从它开始,这里1天= 24 * 60 * 60 * 1000 = 86400000

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