Android SharedPreferences Tutorial and Example

Using AlarmManager to Schedule Android Tasks

Android apps often need to perform work at a particular time, such as showing a reminder, refreshing a local database, or sending a notification. AlarmManager provides a system service for these time-based events, even when your activity is no longer visible.

Using AlarmManager for Scheduling Tasks requires careful handling of Android versions, battery restrictions, time zones, and user permissions. This guide demonstrates a practical Kotlin approach that suits beginner projects while explaining when another scheduling API may be a better fit.

Understanding how AlarmManager works

AlarmManager does not execute your business logic directly. Instead, it delivers a PendingIntent to a BroadcastReceiver when the scheduled time arrives. The receiver then performs a small action, such as creating a notification or starting another component.

A common design is to place scheduling code in an activity or repository, receive the event in a dedicated receiver, and keep the receiver brief. Long-running work should be handed to WorkManager or a foreground service rather than performed inside onReceive(), because the receiver has a limited execution window.

The service supports elapsed-time alarms and real-time alarms. ELAPSED_REALTIME_WAKEUP is useful for intervals measured from device uptime, while RTC_WAKEUP uses wall-clock time. A calendar reminder for 8:00 am should generally use RTC_WAKEUP, because users expect it to follow the clock rather than the time since the phone last booted.

Creating a basic scheduled reminder

Add a receiver to AndroidManifest.xml:

<receiver
    android:name=".ReminderReceiver"
    android:exported="false" />

The following Kotlin function schedules a reminder for a chosen date and time. FLAG_IMMUTABLE is important for modern Android versions, and using a unique request code makes it possible to cancel this particular reminder later.

fun scheduleReminder(context: Context, triggerAtMillis: Long) {
    val alarmManager =
        context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

    val intent = Intent(context, ReminderReceiver::class.java).apply {
        putExtra("message", "Check today's reminder")
    }

    val pendingIntent = PendingIntent.getBroadcast(
        context,
        1001,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )

    alarmManager.setAndAllowWhileIdle(
        AlarmManager.RTC_WAKEUP,
        triggerAtMillis,
        pendingIntent
    )
}

The receiver can display a notification:

class ReminderReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val message = intent.getStringExtra("message") ?: "Reminder"

        NotificationHelper.show(
            context,
            title = "Android reminder",
            message = message
        )
    }
}

On Android 13 and later, the application must request POST_NOTIFICATIONS at runtime before notifications can appear. Create a notification channel on Android 8.0 and newer as well. Without these steps, the alarm may fire correctly while the user sees no visible reminder.

Choosing the right scheduling method

The alarm type should match the reliability and timing requirements of the feature. Exact alarms are appropriate for an alarm-clock style feature, medication reminder, or appointment notification. They consume more scheduling precision, so they should not be used for ordinary background synchronisation.

Requirement Suitable API Timing behaviour Typical example
User-visible event at a precise time AlarmManager exact alarm Close to the requested clock time Medication or meeting reminder
Event that can be delayed WorkManager Runs when system conditions allow Uploading queued data
Repeated flexible background work PeriodicWorkRequest Inexact, system-managed interval Daily content refresh
Immediate ongoing operation Foreground service Runs with visible user notification Navigation or active tracking
Simple in-process delay Coroutine or Handler Stops when the process is killed Temporary screen countdown

Android may defer alarms while the device is in Doze mode. setAndAllowWhileIdle() can deliver an important reminder during idle periods, but it is still subject to system limits. It should not be treated as a way to run frequent background loops.

For Android 12 and newer, exact alarms have additional access requirements. Apps targeting recent SDK versions may need the SCHEDULE_EXACT_ALARM permission, and the user can revoke that access in system settings. Check alarmManager.canScheduleExactAlarms() before using an exact API, then provide a clear path to the relevant settings screen if the feature genuinely depends on exact timing.

Handling repeating alarms and calendar time

Repeating alarms are convenient, but setRepeating() is inexact on current Android releases. For a daily reminder, calculate the next calendar occurrence, schedule a one-shot alarm, and schedule the following occurrence when the receiver runs. This approach handles daylight-saving changes more naturally than adding a fixed number of milliseconds.

Australia makes this distinction especially important. Sydney and Melbourne move between AEST and AEDT, while Brisbane remains on standard time throughout the year. A reminder stored as “8:00 am in the user’s local zone” should use java.time, ZonedDateTime, and the device’s current ZoneId, rather than assuming every Australian city has the same offset.

val zone = ZoneId.systemDefault()
val nextRun = LocalDate.now(zone)
    .plusDays(1)
    .atTime(8, 0)
    .atZone(zone)
    .toInstant()
    .toEpochMilli()

If the device reboots, alarms may be removed. Register a receiver for BOOT_COMPLETED, request the permission, and restore saved reminders from SQLite or SharedPreferences. Store the user’s local time and time zone where possible, rather than saving only a previously calculated timestamp.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver
    android:name=".BootReceiver"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

Cancelling alarms and avoiding common errors

To cancel an alarm, recreate the same PendingIntent details used during scheduling. The request code, receiver class, action, and relevant intent data must match. If the application generates a new request code each time without storing it, the user may be unable to cancel old reminders.

fun cancelReminder(context: Context) {
    val intent = Intent(context, ReminderReceiver::class.java)

    val pendingIntent = PendingIntent.getBroadcast(
        context,
        1001,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )

    val alarmManager =
        context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

    alarmManager.cancel(pendingIntent)
    pendingIntent.cancel()
}

Test with the screen locked, the app removed from recent tasks, battery saver enabled, and the device restarted. Also test around daylight-saving transitions in Melbourne or Sydney, and compare the result with Brisbane, where the clock does not change seasonally.

A reminder app intended for the Australian market should account for users travelling between Perth, Adelaide, Brisbane, and the eastern capitals. Use the device time zone at scheduling time, explain whether an event follows local time or its original location, and avoid promising second-level precision for ordinary Android devices.

Practical implementation recommendations

A robust scheduling feature keeps the alarm as a trigger rather than treating it as a complete background-processing system. Save the reminder data, validate permissions, rebuild alarms after reboot, and hand substantial work to a suitable Android component.

  • Use RTC_WAKEUP for calendar-based reminders and elapsed time for device-uptime intervals.
  • Prefer WorkManager when delayed execution is acceptable or the task involves network and database work.
  • Request notification permission on Android 13 and exact-alarm access only when precise timing is essential.
  • Store unique request codes and reminder details so alarms can be edited, cancelled, and restored.
  • Test AEST, AEDT, and Australian time zones such as Australia/Brisbane and Australia/Perth.

AlarmManager is a focused tool for delivering time-sensitive events. When combined with notification channels, persistent storage, reboot recovery, and modern permission checks, it provides a dependable foundation for reminders and scheduled actions in Android applications.