Explain Codes LogoExplain Codes Logo

Alarm Manager Example

java
alarm-management
android-development
broadcast-receiver
Alex KataevbyAlex Kataev·Sep 9, 2024
TLDR

Schedule tasks in Android using AlarmManager with these steps:

  1. Create Intent for the action to execute.
  2. Encase it in a PendingIntent.
  3. Access AlarmManager by context.getSystemService(Context.ALARM_SERVICE).
  4. Schedule with set(), setRepeating() or setExact().

Setting a 10-second alarm:

Intent intent = new Intent(context, AlarmReceiver.class); PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, 0); AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 10000, pIntent);

Note: Android 6.0 and above should use setExactAndAllowWhileIdle() for precision during Doze Mode.

Creating a simple Alarm

Here's a simple alarm setup that triggers a broadcast:

  • Create a BroadcastReceiver to respond when alarm fires:
public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // Place your task here. Maybe feed your virtual cat? 🐈 } }
  • Register the BroadcastReceiver in AndroidManifest.xml:
<receiver android:name=".AlarmReceiver" />
  • Set up the alarm using the Fast Setup instructions above.

Advanced Alarm Setup

The created alarm is great but it vanishes after a device reboot. For a more persistent alarm setup:

  • Create a Boot receiver: This resets the alarms after the device reboots.
public class BootCompletedReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { // Alarm reset goes here // It's the phoenix of alarm world 🐦🔥 } } }
  • Register Boot Receiver in your AndroidManifest.xml:
<receiver android:name=".BootCompletedReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver>
  • Permissions: Your app needs explicit permissions for using wake locks. Add these in your Manifest.xml:
<uses-permission android:name="android.permission.SET_ALARM"/> <uses-permission android:name="android.permission.WAKE_LOCK"/>

Advanced Alarm Handling

Wake lock with BroadcastReceiver: Ensure tasks run when alarm fires by keeping the CPU running:

public class AlarmReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp:WakelockTag"); wakeLock.acquire(10000); // You have 10 seconds to make coffee! ☕ // Execute task wakeLock.release(); } }

IntentService and AlarmManager combo: For tasks that run a long time, use IntentService with AlarmManager:

public class AlarmService extends IntentService { public AlarmService() { super("AlarmService"); } @Override protected void onHandleIntent(Intent intent) { // Here's a place for your long running task. // Like downloading the entire internet perhaps? 🌐 } }

Managing multiple alarms: Ensure unique PendingIntent request codes and use custom Intent action strings:

Intent i1 = new Intent(this, AlarmReceiver.class); i1.setAction("com.myapp.ALARM_ONE"); PendingIntent alarm1PendingIntent = PendingIntent.getBroadcast(this, 0, i1, 0); Intent i2 = new Intent(this, AlarmReceiver.class); i2.setAction("com.myapp.ALARM_TWO"); PendingIntent alarm2PendingIntent = PendingIntent.getBroadcast(this, 1, i2, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, timeForAlarm1, alarm1PendingIntent); alarmManager.set(AlarmManager.RTC_WAKEUP, timeForAlarm2, alarm2PendingIntent);

Critical Tips for Alarm Management

  • Doze Mode awareness for newer Android versions.
  • Use SystemClock.elapsedRealtime() to schedule inexact repeating alarms that don't need to wake the device up.
  • Be mindful of the impact of frequent alarms on battery life and user experience.