How to Use AlarmManager in android Development
How to Use AlarmManager in android Development
During android development. AlarmManager is often used to regularly send a broadcast, start a Service, or start an Activity. This article will introduce three methods of AlarmManager during development.
1. Use alarm to send a broadcast
First, we need to create an Intent instance. Used to send broadcasts. The Code is as follows:
You can define the action to be sent. The following code sends a CLOCK broadcast every five seconds.
Define a receiver in Manifest to receive CLOCK broadcasts.
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 must be declared in 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 );
To cancel a timer, follow these steps:
Intent I = new Intent ();
I. setAction ("CLOCK ");
I. putExtra ("msg", "alarm start ");
// Parameter 2 is 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 startup
Am. set () // indicates to start only once