Leoa
Leoa

Reputation: 1187

Set Alarm To Alert 5 Minutes Before a certian Time

I'm trying to get Alarm Manager to alert the user 5 minutes before an event happens. How do I go about doing this?

For example, the time of the event is 10:00:00 and I need set the alarm 5 minutes earlier at 9:55:00. I wasn't able to find examples of this in my search.

Is there a date or calendar function that can set an earlier time based on a date?

Below is the incomplete pseudo code

                            int index = eventTime.indexOf(':');
                String Hour =eventTime.substring(0, index);
                String Min = eventTime.substring(index + 1, index + 3);

                Calendar cal = Calendar.getInstance(); 
                int em = Integer.parseInt(eventMonth);
                int ed = Integer.parseInt(eventDay);
                int ey = Integer.parseInt(eventYear);
                int h = Integer.parseInt(Hour);
                int m = Integer.parseInt(Min);

                        int alertTime=5;
                        m=m+alertTime;

                            cal.set(Calendar.MONTH, em);
                cal.set(Calendar.YEAR, ey);
                cal.set(Calendar.DAY_OF_MONTH, ed);
                cal.set(Calendar.HOUR_OF_DAY, h);
                cal.set(Calendar.MINUTE, m);

                            AlarmManager mgr = new AlarmManager();

                             mgr.addAlarm(cal.getTime(), new AlarmListener() {
            // public void handleAlarm(AlarmEntry entry)
            Log.v("calander", cal.toString());
            // }
            // });

Upvotes: 0

Views: 2274

Answers (1)

Andy
Andy

Reputation: 10830

Your pseudo code is on the right track. Though for the AlarmManager you wanna do something like this:

AlarmManager alarm = (AlarmManager)getContext().getSystemService(Activity.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pi);
//pi is a PendingIntent since you want it to run some code at the point it goes off
//Look up PendingIntent on the Android docs to understand what it does if you dont already know

For your date thing using Calendar, you are doing it right. Though it would be cleaner using set() in this way:

set(int year, int month, int day, int hourOfDay, int minute)

In your case, it could look like this:

Calendar cal = Calendar.getInstance();
cal.set(ey, em, ed, h, m-5);

As for whether something exists to make the Calendar based on date, it depends on how you want to do it. For you, I don't really think there is anything else you really can do besides supply the dates and just subtract depending on whether its minutes, hours, etc. Hopefully what I did makes sense and can actually work with what you are trying to do.

Upvotes: 2

Related Questions