How to use Android development Alarmmanager
During the Android development process. Alarmmanager is often used to send a broadcast periodically, or to start a service, or to start an activity. In this paper, we will introduce the three usages of alarmmanager in the development process respectively.
1. Use alarm to send a broadcast
First, we need to create an instance of intent. Used to send broadcasts. The code is as follows:
The action that needs to be sent can be arbitrarily defined, and the following code sends a clock broadcast every five seconds
Need to define a receiver in manifest to receive the clock broadcast
Intent Intent = new Intent (); Intent.setaction ("CLOCK");
Intent.putextra ("msg", "alarm start");
Pendingintent pendingintent = Pendingintent.getbroadcast (this, 0,intent, 0);
Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);
LOG.I (TAG, "Alarm"); am.setrepeating (Alarmmanager.rtc_wakeup,
System.currenttimemillis (), 5*1000, pendingintent);
2, use alarm to start an activity, the code is as follows:
Intent Intent = new Intent ();
Intent.setclass (Mainactivity.this, Alarmactivity.class);
Pendingintent pendingintent = pendingintent.getactivity (this, 0,intent, 0);
Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);
Am.set (Alarmmanager.rtc_wakeup, System.currenttimemillis () + 5*1000, pendingintent);
3, use alarm to start a service, the code is as follows:
The service needs to be declared under manifest.
Intent Intent = new Intent ();
Intent.setclass (Mainactivity.this, Alarmservice.class);
Pendingintent pendingintent = Pendingintent.getservice (this, 0,intent, 0);
Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);
LOG.I (TAG, "Alarm");
Am.set (Alarmmanager.rtc_wakeup, System.currenttimemillis () + 5*1000, pendingintent);
The method of canceling the timer is as follows:
Intent i = new Intent ();
I.setaction ("CLOCK");
I.putextra ("msg", "alarm start");
The parameter 2 is the ID. Cancel alarm with id 0
Pendingintent pendingintent = pendingintent.getbroadcast (this, 0,
I, 0);
Alarmmanager am = (alarmmanager) getsystemservice (Alarm_service);
Am.cancel (pendingintent);
am.setrepeating ()//Indicates periodic start-up
Am.set ()//= start once
How to use Android development Alarmmanager