Question

Android AlarmManager Example: Scheduling Tasks with AlarmManager

kotlinjavaandroidalarmmanager

Question

I want to implement a scheduling feature in my Android project. I searched for examples of using AlarmManager, but I could not find a clear beginner-friendly example.

Can someone show me a basic AlarmManager example program in Android?

Short Answer

By the end of this page, you will understand what Android AlarmManager is, when to use it, how to schedule a future task with it, and how a BroadcastReceiver works together with it. You will also see a complete beginner-friendly example and learn common mistakes to avoid.

Concept

AlarmManager is an Android system service used to schedule work to happen at a specific time in the future, even if your app is not currently open.

In Android, you often need code to run later rather than immediately. For example:

  • show a reminder at 8:00 AM
  • trigger a background action after a delay
  • schedule repeating behavior
  • wake your app to handle time-based events

AlarmManager does not directly run your code. Instead, it usually sends a PendingIntent at the scheduled time. That PendingIntent can:

  • start a BroadcastReceiver
  • start a service
  • launch an activity

A common beginner pattern is:

  1. Get the AlarmManager system service
  2. Create an Intent
  3. Wrap the Intent in a PendingIntent
  4. Schedule it using methods like set()
  5. Receive the alarm in a BroadcastReceiver

Why this matters:

  • Mobile apps often depend on time-based events
  • Android may stop or delay background work if you do it incorrectly
  • AlarmManager is one of the standard tools for scheduled tasks

Important note: in modern Android, AlarmManager is best for time-specific events such as reminders or alarms. For general background work, WorkManager is often preferred.

Mental Model

Think of AlarmManager like setting an alarm clock for your app.

  • AlarmManager is the clock
  • Intent is the note telling Android what should happen
  • PendingIntent is the sealed instruction Android is allowed to use later
  • BroadcastReceiver is the person who hears the alarm and reacts to it

So the process is:

  • You set the alarm now
  • Android keeps track of the time
  • When the time arrives, Android delivers the instruction
  • Your receiver runs the code you prepared
Take Quiz

Syntax and Examples

Basic syntax

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
        this,
        0,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);

long triggerAtMillis = System.currentTimeMillis() + 10_000;

alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, pendingIntent);

What this does

  • getSystemService(Context.ALARM_SERVICE) gets the Android alarm service
  • Intent points to AlarmReceiver
  • PendingIntent.getBroadcast(...) tells Android to send a broadcast later
  • System.currentTimeMillis() + 10_000 means 10 seconds from now
  • set(...) schedules the alarm

Beginner-friendly complete example

MainActivity.java

package com.example.alarmdemo;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        Intent intent = new Intent(this, AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );

        long triggerTime = System.currentTimeMillis() + 5000;

        if (alarmManager != null) {
            alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
            Toast.makeText(this, "Alarm set for 5 seconds later", Toast.LENGTH_SHORT).show();
        }
    }
}

AlarmReceiver.java

package com.example.alarmdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "Alarm triggered!", Toast.LENGTH_LONG).show();
    }
}

AndroidManifest.xml

<application
    ...>

    <receiver android:name=".AlarmReceiver" />

</application>

Explanation

When MainActivity starts, it schedules an alarm for 5 seconds later. When that time arrives, Android sends the broadcast to AlarmReceiver, and the receiver shows a toast.

Step by Step Execution

Consider this code:

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
        this,
        0,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);
long triggerTime = System.currentTimeMillis() + 5000;
alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);

Here is what happens step by step:

  1. getSystemService(Context.ALARM_SERVICE) asks Android for the system alarm scheduler.
  2. An Intent is created that targets AlarmReceiver.
  3. That intent is wrapped in a PendingIntent so Android can use it later on your app's behalf.
  4. System.currentTimeMillis() gets the current time in milliseconds.
  5. + 5000 adds 5 seconds.
  6. alarmManager.set(...) tells Android to fire the PendingIntent at that future time.
  7. After about 5 seconds, Android sends the broadcast.
  8. AlarmReceiver.onReceive(...) runs.
  9. The receiver code shows Alarm triggered!.

Small execution trace

Suppose current time is:

1700000000000

Then:

triggerTime = 1700000005000

At that time, Android delivers the pending intent to your receiver.

Real World Use Cases

AlarmManager is useful when the timing itself is important.

Common real-world uses

  • Reminder apps: trigger a reminder at a specific clock time
  • Medication alerts: notify the user at scheduled intervals
  • Calendar apps: fire event reminders before meetings
  • Wake-up alarms: launch alarm behavior at a chosen time
  • Time-based notifications: send a notification later in the day

Example scenarios

  • A to-do app reminds users about a task at 6:00 PM
  • A prayer time app schedules alerts for each prayer time
  • A study app reminds users every evening to review flashcards

If the job is “run this at a meaningful time,” AlarmManager may fit well.

If the job is “run some background work eventually,” WorkManager is usually better.

Take Quiz

Real Codebase Usage

In real Android projects, developers often use AlarmManager in a few common patterns.

1. Scheduling notifications

A receiver is triggered by AlarmManager, and the receiver creates a notification.

2. Guard clauses

Developers usually check for null and invalid times before scheduling.

if (alarmManager == null) {
    return;
}

if (triggerTime <= System.currentTimeMillis()) {
    return;
}

3. Updating existing alarms

Using the same request code and matching intent lets you replace an existing scheduled alarm.

PendingIntent pendingIntent = PendingIntent.getBroadcast(
        context,
        100,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);

4. Canceling alarms

Real apps often allow the user to turn reminders off.

alarmManager.cancel(pendingIntent);
pendingIntent.cancel();

5. Exact alarms for precise timing

When exact timing matters, developers may use methods like setExact() instead of set().

6. Separating scheduling logic

Instead of placing everything in an activity, real apps often create a helper class such as AlarmScheduler to keep scheduling code organized and reusable.

Common Mistakes

1. Forgetting to register the BroadcastReceiver

If the receiver is not declared in AndroidManifest.xml, the alarm may not reach it.

Broken example:

<!-- Receiver missing -->

Fix:

<receiver android:name=".AlarmReceiver" />

2. Expecting AlarmManager to directly run activity code

AlarmManager usually triggers a PendingIntent, not a random method call in your activity.

Broken idea:

// AlarmManager does not call this method directly later
myMethod();

Fix: schedule a BroadcastReceiver, service, or activity launch.

3. Using the wrong PendingIntent type

If you want to trigger a broadcast, use getBroadcast().

Broken example:

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);

Fix:

PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

4. Ignoring modern Android behavior

Some alarms may be delayed to save battery, especially if exact timing is not required.

How to avoid this:

  • use setExact() when precise time matters
  • use WorkManager for general deferred background work
  • test on modern Android versions

5. Reusing request codes carelessly

If multiple alarms use the same request code and same matching intent, one may overwrite another.

Fix:

  • use distinct request codes for different alarms
  • or intentionally reuse them when updating an existing alarm

6. Scheduling a past time

If the target time is already in the past, behavior may not match your expectations.

Fix:

if (triggerTime > System.currentTimeMillis()) {
    alarmManager.set(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent);
}

Comparisons

set() vs setExact()

MethodMeaningBest for
set()Schedules an alarm, but Android may adjust timing slightlyNon-precise tasks
setExact()Tries to fire at the exact requested timeAlarms, reminders, precise timing

RTC_WAKEUP vs ELAPSED_REALTIME_WAKEUP

TypeUsesTime base
RTC_WAKEUPWall clock timeCurrent date/time via System.currentTimeMillis()
ELAPSED_REALTIME_WAKEUPTime since device bootSystemClock.elapsedRealtime()

AlarmManager vs WorkManager

ToolBest use caseNotes
AlarmManagerExact or time-specific eventsGood for reminders and alarms
WorkManagerDeferrable background workBetter for reliable background tasks

BroadcastReceiver vs Activity

ComponentPurpose
BroadcastReceiverHandles short-lived events like alarms
ActivityDisplays UI and interacts with the user
Take Quiz

Cheat Sheet

Quick reference

Get the service

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Create the target intent

Intent intent = new Intent(this, AlarmReceiver.class);

Wrap it in a pending intent

PendingIntent pendingIntent = PendingIntent.getBroadcast(
        this,
        0,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
);

Schedule an alarm

long time = System.currentTimeMillis() + 5000;
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);

Schedule an exact alarm

alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);

Cancel an alarm

alarmManager.cancel(pendingIntent);
pendingIntent.cancel();

Rules to remember

  • Register your receiver in AndroidManifest.xml
  • Use getBroadcast() for receivers
  • Use unique request codes for different alarms
  • Use setExact() when timing matters
  • Use WorkManager for general background jobs
  • Check for null when getting system services

Edge case

If the app must behave correctly on modern Android versions, test alarm behavior carefully because battery optimizations can affect scheduling.

FAQ

What is AlarmManager in Android?

AlarmManager is a system service that schedules actions to happen at a future time.

Does AlarmManager run code directly?

No. It usually triggers a PendingIntent, which then starts a receiver, service, or activity.

When should I use AlarmManager instead of WorkManager?

Use AlarmManager when the exact time matters, such as reminders or alarm clocks. Use WorkManager for deferred background tasks.

Why is my alarm not firing?

Common reasons include an unregistered receiver, incorrect PendingIntent, duplicate request codes, or modern Android battery restrictions.

What is a BroadcastReceiver used for here?

It receives the alarm event when Android sends the scheduled broadcast.

Can I repeat alarms with AlarmManager?

Yes, Android supports repeating alarms, but many apps now prefer more battery-aware approaches depending on the use case.

Do I need permissions for basic AlarmManager usage?

Basic scheduling often does not require special permissions, but exact alarm behavior can have additional requirements on newer Android versions.

Take Quiz

Mini Project

Description

Build a simple reminder feature that schedules a message to appear a few seconds later using AlarmManager and a BroadcastReceiver. This demonstrates the core pieces you need for time-based scheduling in an Android app.

Goal

Create an Android app that schedules an alarm for 10 seconds in the future and shows a toast when the alarm fires.

Requirements

  1. Create an activity that schedules an alarm when the app opens.
  2. Create a BroadcastReceiver that handles the alarm event.
  3. Register the receiver in AndroidManifest.xml.
  4. Use AlarmManager, Intent, and PendingIntent together.
  5. Show a visible result when the alarm is triggered.
Take Quiz

Keep learning

Related questions

View more