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 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.
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
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:
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 thePendingIntentat that future time.- After about 5 seconds, Android sends the broadcast.
AlarmReceiver.onReceive(...)runs.- 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.
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
WorkManagerfor 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()
| 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 System.currentTimeMillis() |
ELAPSED_REALTIME_WAKEUP | Time since device boot | SystemClock.elapsedRealtime() |
AlarmManager vs WorkManager
| Tool | Best use case | Notes |
|---|---|---|
AlarmManager | Exact or time-specific events | Good for reminders and alarms |
WorkManager | Deferrable background work | Better for reliable background tasks |
BroadcastReceiver vs Activity
| Component | Purpose |
|---|---|
BroadcastReceiver | Handles short-lived events like alarms |
Activity | Displays UI and interacts with the user |
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
WorkManagerfor general background jobs - Check for
nullwhen 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.
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
Accessing Kotlin Extension Functions from Java
Learn how Kotlin extension functions are compiled and how to call them correctly from Java with clear examples and common pitfalls.
Add a Maven Repository URL in Gradle Kotlin DSL (build.gradle.kts)
Learn how to add Maven Central and a custom Maven repository URL in Gradle Kotlin DSL using build.gradle.kts syntax.
Allow HTTP and HTTPS in Android 9 Pie with Network Security Configuration
Learn how Android 9 Pie handles cleartext HTTP traffic and how to allow HTTP and HTTPS safely using network security config.