- Define a BroadcastReceiver to handle whatever actions you want to run when an alarm is received
- Create an activity in which you create the alarm
Creating the BroadcastReceiver
When an alarm goes off it must be received by something. The BroadcastReceiver will receive the alarm and perform whatever action is specified. For this example we will extend BroadcastReceiver to send a text message to a number specified by the calling intent.
You must override onReceive. Here we call sendSMS(intent) which then pulls the message and number for the text from the extras bundle of the passed intent. The text is then sent using the SmsManager.
Android SmsManager Reference
After the receiver is created, it must also be defined in the manifest file for the project.
Creating the Activity
For our receiver to handle an event, one must first be created. There are several types of alarm events (one-time, recurring, etc) and different ways to create them. This example will be simple. We will create an alarm to send our text 10 minutes from the current time.
- Using Android.Calendar you can calculate specific times for an alarm to go off rather than just a general length of time. Ex. You can create an alarm to go off at 1pm each day.
For more on types of events and creation see Android AlarmManager Reference
An important part of this code is the static eventID. Say you have an activity where you want to create multiple alarms to send different texts. If you create the PendingIntent like this
using the same id (20000) for each intent the FLAG_UPDATE_CURRENT will update the existing intent with the same id with the new extras. This will result in only the most recently created alarm being active.
By using the static variable and incrementing it each time, it allows multiple alarms to be active since the intents are not exactly the same each time they are called.
Android PendingIntent Reference
If you changed the "number" string from "Some Phone Number" to a valid number, this activity would result in the message "Hello World" being sent to the specified number 10 minutes after the code was fun.