Question
Android AlarmManager Example: Scheduling Tasks with AlarmManager
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:
- Get the
AlarmManagersystem service - Create an
Intent - Wrap the
Intentin aPendingIntent - Schedule it using methods like
set() - 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
AlarmManageris one of the standard tools for scheduled tasks
Important note: in modern Android, AlarmManager is best for events such as reminders or alarms. For general background work, is often preferred.
Mental Model
Think of AlarmManager like setting an alarm clock for your app.
AlarmManageris the clockIntentis the note telling Android what should happenPendingIntentis the sealed instruction Android is allowed to use laterBroadcastReceiveris 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
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 serviceIntentpoints toAlarmReceiverPendingIntent.getBroadcast(...)tells Android to send a broadcast laterSystem.currentTimeMillis() + 10_000means 10 seconds from nowset(...)schedules the alarm
Beginner-friendly complete example
MainActivity.java
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:
getSystemService(Context.ALARM_SERVICE)asks Android for the system alarm scheduler.- An
Intentis created that targetsAlarmReceiver. - That intent is wrapped in a
PendingIntentso Android can use it later on your app's behalf. System.currentTimeMillis()gets the current time in milliseconds.+ 5000adds 5 seconds.alarmManager.set(...)tells Android to fire the at that future time.
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.
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 .
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:
Comparisons
set() vs setExact()
| Method | Meaning | Best for |
|---|---|---|
set() | Schedules an alarm, but Android may adjust timing slightly | Non-precise tasks |
setExact() | Tries to fire at the exact requested time | Alarms, reminders, precise timing |
RTC_WAKEUP vs ELAPSED_REALTIME_WAKEUP
| Type | Uses | Time base |
|---|---|---|
RTC_WAKEUP | Wall clock time | Current date/time via |
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
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?
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
- Create an activity that schedules an alarm when the app opens.
- Create a
BroadcastReceiverthat handles the alarm event. - Register the receiver in
AndroidManifest.xml. - Use
AlarmManager,Intent, andPendingIntenttogether. - Show a visible result when the alarm is triggered.
Keep learning
Related questions
Can You Extend a Data Class in Kotlin? Inheritance, Limits, and Better Alternatives
Learn why Kotlin data classes cannot be extended, what causes the component function clash, and which alternatives to use instead.
Difference Between List and Array in Kotlin
Learn the difference between List and Array in Kotlin, including mutability, size, APIs, performance, and when to use each one.
Fix KaptExecution Error in Android Kotlin: Data Binding and Build Generation
Learn why KaptExecution fails in Android Kotlin builds, especially with data binding and generated classes, and how to fix it step by step.