Step 2: Setup in Activity

Here is an all-in-one code snippet and will be described part-by-part:

Step 2 — Part 1 : Get AlarmManager instance

As mentioned at the start of this article, AlarmManager is actually a system service and thus can be retrieved from Context.getSystemService() function with parameter Context.ALARM_SERVICE .

Step 2 — Part 2 : Prepare for an Intent

Android allows a bundle of information to be sent to a target receiver (i.e. AlarmReceiver , which is defined in step 1) when alarm goes off. The designated receiver and the corresponding information can be set in Intent by setting its action and extra . These information can later be retrieved at the onReceive() callback in the designated BroadcastReceiver and action field is checked to ensure the correctness of the system broadcast.

Step 2 — Part 3 : Prepare for a PendingIntent

PendingIntent is a reference pointing to a token maintained by the Android system. Thus, it will still be valid if the application is killed by user and can be broadcasted at some moment in the future.

There are totally 4 functions for initialising a PendingIntent but only 1 of them is applicable:

PendingIntent.getBroadcast() — Applicable to AlarmManager PendingIntent.getActivity() PendingIntent.getActivities() PendingIntent.getService()

As mentioned before, AlarmManager will send a broadcast to the registered BroadcastReceiver ( AlarmReceiver in this example). By official documentation, only getBroadcast() is applicable for AlarmManager.

Retrieve a PendingIntent that will perform a broadcast, like calling Context#sendBroadcast(Intent) . Reference: Google official documentation — PendingIntent.getBroadcast()

The request code can be treated as an identifier for different PendingIntent tokens with the same Intent . In other words, it is only useful when you want multiple PendingIntent to have the same Intent .

Determine if two intents are the same for the purposes of intent resolution (filtering). That is, if their action, data, type, identity, class, and categories are the same. This does not compare any extra data included in the intents. Reference: Google official documentation — Intent.filterEquals()

Flags indicates how system should handle the new and existing PendingIntent s that have the same Intent . 0 indicates that system will use its default way to handle the creation of PendingIntent . The following are some examples:

FLAG_UPDATE_CURRENT FLAG_CANCEL_CURRENT FLAG_IMMUTABLE

Step 2 — Part 4 : Set the alarm time and send to system