SoFunction
Updated on 2025-03-11

AlarmManager+Notification implements the timed notification and reminder function in Android

Introduction to AlarmManager

AlarmManager is essentially a global timer, a system-level prompt service commonly used in Android, which starts other components (including Activity, Service, BroadcastReceiver) at a specified time or periodically. This article will explain how to use AlarmManager to implement the timed reminder function.

Alarm clock configuration

Cycle alarm clock

Intent intent = new Intent();
(GlobalValues.TIMER_ACTION_REPEATING);
PendingIntent sender = (context, 0, intent, 0);
AlarmManager alarm = (AlarmManager) (Context.ALARM_SERVICE);
(AlarmManager.RTC_WAKEUP, () + 5 * 1000, 3 * 1000, sender);
setRepeating(int type,long startTime,long intervalTime,PendingIntent pi)

This method is used to set a timed service that is executed periodically. type: alarm clock type, startTime: alarm clock first execution time, intervalTime: interval time between the two executions of alarm clock, pi: alarm clock response action.

setInexactRepeating(int type,long startTime,long intervalTime,PendingIntent pi)

This method is also used to set up periodic fixed services, similar to the previous one. However, the interval between the execution of the two alarm clocks is not fixed. It is relatively more power-saving, because the system may combine several similar alarm clocks into one to perform, reducing the number of wake-up times of the device.

intervalTime built-in variable

One day apart: INTERVAL_DAY
Half a day interval: INTERVAL_HALF_DAY
15 minutes interval: INTERVAL_FIFTEEN_MINUTES
Half an hour apart: INTERVAL_HALF_HOUR
One hour apart: INTERVAL_HOUR

Timed alarm clock

// Obtain the object of the AlarmManager service provided by the systemAlarmManager alarm = (AlarmManager) (Context.ALARM_SERVICE);
//Intent sets the component to be started, and the broadcast is started hereIntent myIntent = new Intent();
(GlobalValues.TIMER_ACTION);
//PendingIntent object sets the action, is it initiated the Activity or Service, or broadcast!PendingIntent sender = (context, 0, myIntent,0);
//Register alarm clock(AlarmManager.RTC_WAKEUP, () + 5 * 1000, sender);
set(int type,long startTime,PendingIntent pi)

This method is used to set a one-time scheduled service. type: alarm clock type, startTime: alarm clock execution time, pi: alarm clock response action.

Cancel the alarm clock

Intent myIntent = new Intent();
(GlobalValues.TIMER_ACTION);
//(GlobalValues.TIMER_ACTION_REPEATING);
PendingIntent sender = (context, 0, myIntent,0);
AlarmManager alarm = (AlarmManager) (Context.ALARM_SERVICE);
(sender);

Set multiple alarm clocks:

If multiple alarm clocks are set continuously, only the last alarm clock will take effect. So how do we deal with this situation? Actually very simple. We can set a unique id for each alarm clock and pass in the second parameter of getBroadcast(). Here, I will increase 1 for each id and save it into Shareprefrence to ensure the uniqueness of the id.

 //Set different IDs for each alarm clock to prevent overwriteint alarmId = (context, "alarm_id", 0);
(context, "alarm_id", ++alarmId);
PendingIntent sender = (context, alarmId, myIntent, 0);

When canceling the alarm, we can also turn off different alarms according to this id.

Detailed explanation of parameters

type: alarm clock type

ELAPSED_REALTIME: After the specified delay is passed, the broadcast is sent, but the device is not awakened (the alarm clock is not available in sleep). If the alarm is triggered while the system is sleeping, it will not be passed until the next device wakes up.

ELAPSED_REALTIME_WAKEUP: After the specified delay is over, the broadcast is sent and the device is awakened (the corresponding component of the operation will be executed even if the operation is shut down). Delay must be counted as the system startup time () is started.

RTC: Specifies the device corresponding to the operation when the value returned by the system call() method is equal to triggerAtTime (at the specified time, the broadcast is sent, but the device is not awakened). If the alarm is triggered while the system is sleeping, it will not be passed until the next device wakes up (the alarm is not available in sleep).

RTC_WAKEUP: Specifies the device corresponding to the operation when the value returned by the system call() method is equal to triggerAtTime (at the specified time, the broadcast is sent and the device is awakened). Even if the system shuts down, the corresponding components of the operation will be executed.

POWER_OFF_WAKEUP: It means that the alarm clock can also perform prompt function normally when the mobile phone is turned off, so it is one of the most used states among the 5 states. In this state, the alarm clock also uses absolute time, and the state value is 4; however, this state seems to be affected by the SDK version, and some versions do not support it.

long intervalTime: execution time

The first execution time of the alarm clock is in milliseconds and can be customized, but the current time is generally used. It should be noted that this attribute is closely related to the first attribute (type). If the alarm clock corresponding to the first parameter uses relative time (ELAPSED_REALTIME and ELAPSED_REALTIME_WAKEUP), then this attribute must use relative time (relative to the system startup time). For example, the current time is expressed as: (); If the alarm clock corresponding to the first parameter uses absolute time (RTC, RTC_WAKEUP, POWER_OFF_WAKEUP), then this attribute must use absolute time, for example, the current time is expressed as: ()

long startTime: interval time

For the periodic timing method, this attribute exists, which indicates the interval time between the two alarm clock executions, which is also in milliseconds.

PendingIntent pi: execute action

It is the execution action of the alarm clock, such as sending a broadcast, giving a prompt, etc. PendingIntent is an encapsulation class of Intent. It should be noted that if the alarm prompt is implemented by starting the service, the PendingIntent object should be obtained by using the (Context c, int i, Intent intent, int j) method; if the alarm prompt is implemented by broadcast, the (Context c, int i, Intent intent, int j) method should be obtained by using the (Context c, int i, Intent intent, int j) method; if the alarm prompt is implemented by using the Activity method, the PendingIntent object should be obtained by using the (Context c, int i, Intent intent, int j) method. If these three methods are used incorrectly, although there will be no error, the alarm clock prompt effect will not be seen. .

Broadcast configuration

Create a new alarm clock BroadCastReceiver:

public class AlarmReceiver extends BroadcastReceiver {
 private NotificationManager m_notificationMgr = null;
 private static final int NOTIFICATION_FLAG = 3;
 @Override
 public void onReceive(Context context, Intent intent) {
  m_notificationMgr = (NotificationManager) (Context.NOTIFICATION_SERVIC
  if (().equals(GlobalValues.TIMER_ACTION_REPEATING)) {
   ("alarm_receiver", "Cycle Alarm Clock");
  } else if (().equals(GlobalValues.TIMER_ACTION)) {
   ("alarm_receiver", "Timed Alarm Clock");
      Bitmap bitmap = ((), );
   Intent intent1 = new Intent(context, );
   PendingIntent pendingIntent = (context, 0, intent1, 0);
   Notification notify = new (context)
     .setSmallIcon() // Set small pictures in the status bar, the size is generally recommended to be 24×24     .setLargeIcon(bitmap) // You can also set large icons here     .setTicker("Family Calendar") // Set the displayed prompt text     .setContentTitle("Family Calendar") // Set the displayed title     .setContentText("You have a diary reminder") // Details of the message     .setContentIntent(pendingIntent) // Associate PendingIntent     .setNumber(1) // The number displayed on the right side of the TextView can be defined externally, click the accumulated setNumber(count), and the sum displayed at this time     .getNotification(); // It should be noted that build() is added in API level16 and after. In API11, getNotificatin() can be used to    |= Notification.FLAG_AUTO_CANCEL;
   NotificationManager manager = (NotificationManager) (
   (NOTIFICATION_FLAG, notify);
   (); //Recycle bitmap  }
 }
}

Register BroadCastReceiver:

Finally, don't forget to register the broadcast on the list.

<!--Alarm clock receiving broadcast-->
<receiver android:name=".">
 <intent-filter>
  <action android:name="com.e_eduspace.TIMER_ACTION_REPEATING" />
  <action android:name="com.e_eduspace.TIMER_ACTION" />
 </intent-filter>
</receiver>

appendix

constant:

public class GlobalValues {
 // Periodic alarm clock public final static String TIMER_ACTION_REPEATING = "com.e_eduspace.TIMER_ACTION_REPEATING";
 // Timed alarm clock public final static String TIMER_ACTION = "com.e_eduspace.TIMER_ACTION";
}

Tools

package com.e_eduspace.;

import ;
import ;
import ;
import ;

import ;

/**
  * Alarm clock timing tool category
  *
  * @author xulei
  * @time 2016/12/13 10:03
  */

public class AlarmTimer {

 /**
   * Set periodic alarm clock
   *
   * @param context
   * @param firstTime
   * @param cycTime
   * @param action
   * @param AlarmManagerType The type of alarm clock, there are 5 commonly used values: AlarmManager.ELAPSED_REALTIME,
   * AlarmManager.ELAPSED_REALTIME_WAKEUP,
   * AlarmManager.RTC_WAKEUP, AlarmManager.POWER_OFF_WAKEUP
   */
 public static void setRepeatingAlarmTimer(Context context, long firstTime,
            long cycTime, String action, int AlarmManagerType) {
  Intent myIntent = new Intent();
  (action);
  PendingIntent sender = (context, 0, myIntent, 0);
  AlarmManager alarm = (AlarmManager) (Context.ALARM_SERVICE);
  (AlarmManagerType, firstTime, cycTime, sender);
  //param1: alarm clock type, param1: alarm clock first execution time, param1: interval between alarm clock execution, param1: alarm clock response action. }

 /**
   * Set the timing alarm clock
   *
   * @param context
   * @param cycTime
   * @param action
   * @param AlarmManagerType The type of alarm clock, there are 5 commonly used values: AlarmManager.ELAPSED_REALTIME,
   * AlarmManager.ELAPSED_REALTIME_WAKEUP,
   * AlarmManager.RTC_WAKEUP, AlarmManager.POWER_OFF_WAKEUP
   */
 public static void setAlarmTimer(Context context, long cycTime,
          String action, int AlarmManagerType, CalendarDay date) {
  Intent myIntent = new Intent();
  //Delivery timed date  ("date", date);
  (action);
  //Set different IDs for each alarm clock to prevent overwrite  int alarmId = (context, "alarm_id", 0);
  (context, "alarm_id", ++alarmId);
  PendingIntent sender = (context, alarmId, myIntent, 0);
  AlarmManager alarm = (AlarmManager) (Context.ALARM_SERVICE);
  (AlarmManagerType, cycTime, sender);
 }

 /**
   * Cancel the alarm clock
   *
   * @param context
   * @param action
   */
 public static void cancelAlarmTimer(Context context, String action) {
  Intent myIntent = new Intent();
  (action);
  PendingIntent sender = (context, 0, myIntent,0);
  AlarmManager alarm = (AlarmManager) (Context.ALARM_SERVICE);
  (sender);
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.