Some of the usage mechanisms of alarmmanager are called Global timers and some are called alarm clocks. Through its use, I personally think it is more appropriate to call a global timer. In fact, its role is similar to that of timer. There are two similar usage: (1) execute an operation after the specified duration (2) Periodically execute an operation
When the alarmmanager object is used with intent, you can enable an activity regularly, send a broadcast, or enable a service.
The following code details the use of two timing methods:
(1) perform an operation after the specified duration
Code
// Operation: Send a broadcast. After receiving the broadcast, the toast prompts that the scheduled operation is completed.
Intent intent = new intent (main. This, alarmreceiver. Class );
Intent. setaction ("short ");
Pendingintent sender =
Pendingintent. getbroadcast (main. This, 0, intent, 0 );
// Set a time in five seconds
Calendar calendar = calendar. getinstance ();
Calendar. settimeinmillis (system. currenttimemillis ());
Calendar. Add (calendar. Second, 5 );
Alarmmanager alarm = (alarmmanager) getsystemservice (alarm_service );
Alarm. Set (alarmmanager. rtc_wakeup, calendar. gettimeinmillis (), Sender );
// Or the following method is simplified
// Alarm. Set (alarmmanager. rtc_wakeup, system. currenttimemillis () + 5*1000, Sender );
Toast. maketext (main. This, "enable alarm after five seconds", Toast. length_long). Show ();
// Note: the consumer remembers to register in manifest. xml.
Code
public static class alarmreceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals("short")){
Toast.makeText(context, "short alarm", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(context, "repeating alarm", Toast.LENGTH_LONG).show();
}
}
}
(2) Periodically execute an operation
Code
Intent intent = new intent (main. This, alarmreceiver. Class );
Intent. setaction ("repeating ");
Pendingintent sender = pendingintent
. Getbroadcast (main. This, 0, intent, 0 );
// Start time
Long firstime = systemclock. elapsedrealtime ();
Alarmmanager AM = (alarmmanager) getsystemservice (alarm_service); // sends broadcasts continuously for a cycle of 5 seconds.
Am. setrepeating (alarmmanager. elapsed_realtime_wakeup
, Firstime, 5*1000, Sender );
The setrepeating () of alarmmanager is equivalent to the Schedule (task, delay, peroid) of timer. In some differences, the timer method specifies the delay time.
Periodically execute tasks in the future;
Cancellation of alarmmanager: (it must be noted that the canceled intent must be absolutely consistent with the intent to be started before alarmmanager can be canceled)
Code
Intent intent =new Intent(Main.this, alarmreceiver.class);
intent.setAction("repeating");
PendingIntent sender=PendingIntent
.getBroadcast(Main.this, 0, intent, 0);
AlarmManager alarm=(AlarmManager)getSystemService(ALARM_SERVICE);
alarm.cancel(sender);