5 - 7 - Alarms (17-43)

7
Hi, I'm Adam Porter, and this is Programming Mobile Applications for Android Handheld Systems. The example applications that we've studied up to now have made decisions and then taken action, now. But what if your application makes a decision, but wants to take an action an hour from now, tomorrow at midnight, or every 15 minutes from now on? In that case, your application will need to create and set alarms. In this lesson, I'll start by discussing what alarms are and how they're used. Next, I'll discuss the Android AlarmManager and the APIs it provides for setting and canceling alarms. After that, I'll discuss the various types of alarms that Android supports. And finally, I'll present and discuss an example application that uses alarms. Now in a nutshell, alarms are a mechanism for sending intents at some point, or points, in the future. And this is useful because it allows an application to cause some other code to execute even when that application is no longer running. Once alarms have been created and registered, they're retained and monitored even if the device goes to sleep. And as we'll talk about later, depending on how you configure an alarm, if it goes off while the device is sleeping, the device can be woken up to handle the alarm, or the alarm can be retained until the next time the device wakes up. And alarms will continue to be active until the device shuts down. On shutdown, all registered alarms will be canceled. To give you some examples of alarms, the other day, I was digging through some Android source code and came across several applications that use alarms. For instance, the MMS messaging application uses alarms to start a service that can find MMS messages that haven't been delivered and can try again to deliver them. The Settings application can made a device discoverable

Transcript of 5 - 7 - Alarms (17-43)

Page 1: 5 - 7 - Alarms (17-43)

Hi, I'm Adam Porter, and this isProgramming MobileApplications for Android Handheld Systems.The example applications that we'vestudied up to now have made decisionsand then taken action, now.But whatif your application makes a decision, butwants to take an action an hour fromnow, tomorrow at midnight, or every 15minutes from now on?In that case, your application will needto create and set alarms.In this lesson, I'll start by discussingwhat alarms are and how they're used.Next, I'll discuss the AndroidAlarmManager andthe APIs it provides for setting andcanceling alarms.After that, I'll discuss the various typesof alarms that Android supports.And finally, I'll present and discuss anexample application that uses alarms.Now in a nutshell, alarms are a mechanismfor sending intentsat some point, or points, in the future.And this is usefulbecause it allows an application to causesome other codeto execute even when that application isno longer running.Once alarms have been created andregistered, they're retainedand monitored even if the device goes tosleep.And as we'll talk about later, dependingon how you configurean alarm, if it goes off while the deviceis sleeping, thedevice can be woken up to handle thealarm, or thealarm can be retained until the next timethe device wakes up.And alarms will continue tobe active until the device shuts down.On shutdown, all registered alarms will becanceled.To give you some examples of alarms, theother day, I was diggingthrough some Android source code andcame across several applications that usealarms.For instance, the MMS messagingapplication usesalarms to start a service that canfind MMS messages that haven't beendeliveredand can try again to deliver them.The Settings application can made a devicediscoverable

Page 2: 5 - 7 - Alarms (17-43)

over Bluetooth.And when it does this, that applicationsets an alarm, and when thealarm goes off, the application makes thedevice not discoverable anymore.And the Phone application keeps a cache ofuser information.This application uses alarms toperiodically update that cache.If you want to use alarmsin your own applications, you do so byinteracting with the AlarmManager service.To get a reference to this service, youcall the context classes GetSystemService,passing in the name of the service, inthis case, Alarm_Service as a parameter.Once you have a reference to theAlarmManager, you canthen use some of its methods to create andset alarms.For instance, you can use the Set methodto set a single alarm.And this method has three parameters.A type, which we'll discuss shortly, along, representing the time at which thealarm should go off and a PeningIntent,which encapsulates the operation thatshould occurwhen the alarm finally does go off.[BLANK_AUDIO]You can use this method, setRepeating, tosetan alarm that repeatedly goes off atspecific intervals.This method has four parameters, the threewe saw in the Set method and an additionallong that specifies the amount of timebetweeneach successive time that the alarm goesoff.Another AlarmManager method issetInexactRepeating.This method is similar to setRepeating, inthat the alarm should go off periodically,but this method gives Android moreflexibilityin deciding exactly when to fire thealarms.For instance, Android might batch upmultiplealarms of this kind and fire them atthe same time so as not to wake up thedevice too many times.And if you want to have this kind ofbehavior, then your time interval must beone of the following constants, whichspecifies intervals of 15 minutes, 30minutes, one hour, 12 hours, and 24 hours.And if you don't use one of theseconstants, then the behavior of the

Page 3: 5 - 7 - Alarms (17-43)

alarms is the same thing that youwould have gotten had you usedsetRepeating instead.Now each of the three methods I justshowed you took a parameter called Type.Let's talk about alarm types now.Android provides two degrees ofconfigurability with respect to alarms.One has to do with how time information isinterpreted, and the othertells Android how to respond if the deviceis sleeping when the alarm fires.Let's look at each of these one at a time.First, you remember that each of the alarmsetting methods took a longas a parameter, and I said that, that longrepresented a time.Android alarms can interpret this longvalue in two different ways.One, it can consider it to be a real orwall clocktime, and in this case, thelong represents the number of millisecondssincemidnight January 1, 1970.And two, it can interpret it to be a, thesystem's up time, andthat is, the amount of time since the timeat which the system last booted up.The second issue, is what should Androiddo if the alarmgoes, if, when the alarm goes off, thedevice is sleeping.One possibilityis to wake up the device now, and deliverthe intent.Another choice, is to let the devicecontinue sleeping, andto deliver the intent, the next time, thedevice wakes up.So, putting all those together, there arefour possibilities, defined as follows.RTC_WAKEUP.Fire the alarm at the specified wall clocktime.If the device is asleep, wake it now anddeliver the intent.RTC.Fire the alarm at the specified wall clocktime, butif the device is asleep, don't wake it upnow.Instead, deliver the intent when thedevice next wakes up.And there is ELAPSED_REALTIME andELAPSED_REALTIME_WAKEUP.For these two types of alarms, Androidfires the alarm when thedevice has been up for the specified time,and if the device

Page 4: 5 - 7 - Alarms (17-43)

is sleeping when the alarm goes off, itwill not be woken up withELAPSED_REALTIME.It will be woken up withELAPSED_REALTIME_WAKEUP.The last part ofthe AlarmManager APIs that we'll discussis the PendingIntent.As we discussed back in usernotifications, a PendingIntent holds aregular intent and essentially serves as apermission slip, in which onecomponent allows a second component to usethe underlying intentas if it were the first component.Three methods that can be usedto create a PendingIntent are getActivity,which returns aPendingIntent that can be used to start anactivity.GetBroadcast, which returns aPendingIntent thatcan be used to broadcast an intent.And getService, which returns aPendingIntent thatcan be used to start a service.So now that we've learned about alarms,let's take a look at an exampleapplication called AlarmCreate.This application uses alarms to gentlyencourage a student tostop playing video games and return to hisor her studies.Let's take a look.Here'smy device.I'll now start up the AlarmCreateapplication.The application displays a simple userinterface with four buttons.One button, labeled Set Single Alarm, thatsetsa single alarm to go off in two minutes.One button, labeled Set Repeating Alarm,that sets a repeating alarm that willgo off in two minutes, and then continueto go off every 15 minutes after that.One button, labeled Set Inexact RepeatingAlarm, that sets arepeating alarm that should go off every15 minutes starting in about two minutes.Now because this is an inexact alarm,Android will try to fire the alarm every15 minutes but will exercise a lot offlexibility in when exactly those alarmsgo off.And finally, one button labelled CancelRepeating Alarm, and thatwill cancel any currently active repeatingor inexact repeating alarms.

Page 5: 5 - 7 - Alarms (17-43)

Now, I'll click the button labeled SetSingle Alarm,and as you can see, the toast messagesuggeststhat the application has now set a singlealarm,and in this case, the alarm should go offintwo minutes.And when it does, the code willplace a user notification in thenotification area.Let's come back at that point and see whathappens.So, now we're back watching the device,and there's the notificationasking if I'm playing Angry Birds again.Let me pull down on the notification area.The notification view tells me that thisisa kind reminder to get back to studying.If I click on this notification view,the AlarmCreate application gets broughtback up.Now before we move forward, let's take alook at the source code for thisapplication.Now here I've opened the application intheIDE, and now I'll open the main activity.Let's take a look at the onCreate method.First, the code gets a reference to theAlarmManager service.Next, the code creates an intent whosetarget is the alarm notification receiverclass.This intent is then wrapped in aPendingIntent that will cause this intentto be broadcast.And after that, the code creates a secondintent, which this time istargeted to another class calledAlarmLoggerReceiver.And as before, this intent is wrapped in aPendingIntent thatwill ultimately cause the intent to bebroadcast to that receiver.Now,scrolling down, the code sets up the fourbuttons that we saw earlier.The first button, when pressed, will setup two one-shot alarms.The first alarm is scheduled to go off twominutes after the button is pressed.The second of this pair will go off aboutfive seconds later.The second button, when pressed,will set up a pair of repeating alarms.The first alarm is scheduled to go off intwo minutes, or two minutes

Page 6: 5 - 7 - Alarms (17-43)

after the button is pressed, and then gooff every 15 minutes after that.The second alarm of the pair will go offabout five seconds after the first.The third button, when pressed, will setup two inexact repeating alarms.The first alarm is scheduled to go offroughly every15 minutes, starting two minutes after thebutton is pressed.And again, the second alarm is scheduledtogo off about five seconds after the first.Now remember, because this is an inexactrepeating alarm, Android hasconsiderable flexibility in the exacttiming of both of those alarms.And in particular, Android will try tominimize thenumber of times it needs to wake up thedevice if it's sleeping, for instance, bygrouping separatealarms to go off roughly at the same time.Finally, the fourth button, when pressed,will cancel existing alarms.In particular, this is important forrepeating alarms, which will continueto go off until they're cancelled or untilthe device shuts down.Returning back to the running application,I'll now pressthe Set Repeating Alarm button, and thissets somenew repeating alarms that will first gooff intwo minutes and then every 15 minutesafter that.[BLANK_AUDIO]Let's come back when we're ready.Okay, so we're back now, and it's beenabout two minutes since the alarms wereset.There's the notification showing that thealarm went off.The next alarm will come along in about 15minutes.Let's take a break now, and when we comeback, we'll examine the LogCat output forthis application.So a bit more than 15 minutes haspassed, and here's the application open inthe IDE.I'll now expand the LogCat view, and I'llfilter the LogCatoutput to just show log messages that havea tag coming from this application.I'll type tag:alarm, and that leaves justthemessages that we're interested in now.As you can see, there are four messages,

Page 7: 5 - 7 - Alarms (17-43)

two from the first time the alarmsfired, and two more from when the alarmswent off again after 15 minutes.And notice that the two alarms which werescheduled to go off with fiveseconds between them, do in fact go offwith that interval of time between them.So those were repeating alarms.Let's go back now to the application andtake a look atwhat happens when we use theSetInexactRepeating method to set thesesame alarms.So here's my device again.And now I'll pull down on the notificationareaand use it to go back to the application.First, I'll cancel the existing alarms,andnext I'll set the inexact repeatingalarms.So let's let the application run forawhile, and thenwe'll take another look at the LogCatoutput for this application.So here we are back in the IDE, andabout 20 minutes has passed since we lasttalked.Let's go back to the LogCat view.And here you can see that there are nowfour new messages, two from the first timethe alarms fired and two more from thesecond time those alarms went off.And some things to notice are that eventhough at 11:19, we set the alarms to gooff starting in two minutes, the first setofalarms actually went off after four orfive minutes.And the second thing to notice, is thateventhough the pair of alarms were scheduledto gooff with a five second delay between them,Androidhas actually fired them at essentially thesame time.And again, because these are inexactrepeating alarms,Android was free to modify the exact alarmtimings.So that's all for our lesson on alarms.Please join me next time for a discussionof networking.See you then.[BLANK_AUDIO]