简体   繁体   中英

How to set an alarm over a specific date range?

I've searching for this requirement from a very longtime and couldn't find anything. So i'm seeking help from you guys.

I've a requirement where i need to set an alarm manager over a specfic date range. I mean from 28-Sept-2016 to 30-Sept-2016 at specific time say 13:00.

Currently i can able to set for the particular day. But not for the date range. My current is as below.

AlarmManager objAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);              
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2016);
        calendar.set(Calendar.MONTH, 8);
        calendar.set(Calendar.DAY_OF_MONTH, 28);
        calendar.set(Calendar.HOUR_OF_DAY, 13);
        calendar.set(Calendar.MINUTE, 00);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        calendar.set(Calendar.AM_PM, Calendar.AM);         

        Intent alamShowIntent = new Intent(this,AlarmActivity.class);
        PendingIntent alarmPendingIntent = PendingIntent.getActivity(this, 0,alamShowIntent,0 );

        objAlarmManager.set(AlarmManager.RTC_WAKEUP,objCalendar.getTimeInMillis(), alarmPendingIntent);

Could you please help me in this regard.

One idea which coming up in mind is to find the delta between the date range and repeat the alarm for soo many days for that particular time. Is this the right approach?

Regards, Sharath

  1. Schedule the first alarm for September 28th, 2016 at 13.00h.
  2. In the code that runs when the alarm is fired, reschedule the alarm. Use the current date and add 24 hours so that it fires same time tomorrow.
  3. Do step 2 unless the date is passed September 30th. The alarm will not be rescheduled and will not fire anymore.

This approach requires you to not use a repeating alarm like setRepeating() . This is however convenient in case you are developing for android 6.0+, since repeating alarms don't fire in doze mode.

There is no way through which you can provide expiry to the alarm while setting new alarm. I will suggest to put your alarm expiry date to the intent ie alamShowIntent & use setRepeating() alarm for the required time. on every alarm event, do check the end date should be greater than the time alarm fired. If it is then do your task & if not then Cancel the alarm with same 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