Alarm Controller demonstrates how to use the Alarm event in an Android application, and its functionality is similar to that of Java.util.Timer, TimerTask. However, alarm can do schedule a task at a specified time, even if the current application exits.
Alarmmanager is used to manage alarm events, to support single execution or repeat execution. Like most Android services, Alarmmanager also uses Getsystemservice to get service objects:
Alarmmanager am
= (alarmmanager) getsystemservice (Alarm_service);
The task description type corresponding to the TimerTask is Pendingintent, Pendingintent describes the intent,pendingintent that will be executed without providing a constructor, and needs to pass the static function getactivity ( context, int, Intent, int), getbroadcast (context, int, Intent, int), GetService (context, int, Intent, int) or want to execute the Activi Ty,broadcast,service description.
In this case, a description of the broadcast oneshotalarm and Repeatingalarm is obtained, corresponding to the broadcast event performed on a single execution, and the broadcast event multiple executions. They are defined in Androidmanifest.xml as broadcast Receiver:
<receiver android:name= ". App. Oneshotalarm "android:process=": Remote "/>
<receiver android:name= ". App. Repeatingalarm "android:process=": Remote "/>
The schedule single Alarm event code is as follows:
Intent Intent = new Intent (alarmcontroller.this, oneshotalarm.class);
Pendingintent sender = Pendingintent.getbroadcast (Alarmcontroller.this,
0, intent, 0);
We want the "alarm to go" seconds from now.
Calendar calendar = Calendar.getinstance ();
Calendar.settimeinmillis (System.currenttimemillis ());
Calendar.add (Calendar.second);
Schedule the alarm!
Alarmmanager am = (alarmmanager) getsystemservice (alarm_service);
Am.set (Alarmmanager.rtc_wakeup, Calendar.gettimeinmillis (), sender);
Where sender is a description of intent sent to broadcast Receiver Oneshotalarm, when the specified time is reached (30 seconds in the example), Alarmmanager sends a oneshotalarm to broadcast When Intent,oneshotalarm is received, a message will be displayed on the screen using toast. If you click "One Shot Alarm" multiple times, you will not schedule multiple Alarm events, because schedule the same sender object, and then cancel the event on this scheduled.