📅  最后修改于: 2023-12-03 14:59:14.954000             🧑  作者: Mango
Android AlarmManager is a class in Android that allows you to schedule your application to perform a task at a later time. It is typically used to schedule a service to run at a specific time or to repeatedly trigger a broadcast receiver.
AlarmManager uses the system clock to schedule events. It is a powerful mechanism that allows developers to create an intelligent and efficient application.
AlarmManager supports three types of alarms:
RTC_WAKEUP alarm is used to wake up the device from sleep mode and triggers the alarm. This alarm is ideal for scheduling recurring events such as checking for new emails.
Example:
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
long timeInMillis = System.currentTimeMillis() + 300000; //Trigger alarm in 5 minutes
alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
In this example, we use RTC_WAKEUP to trigger an alarm in 5 minutes using a broadcast receiver.
RTC alarm is similar to RTC_WAKEUP alarm but does not wake up the device from sleep. This alarm is useful for scheduling events that do not require immediate attention.
Example:
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
long timeInMillis = System.currentTimeMillis() + 300000; //Trigger alarm in 5 minutes
alarmManager.set(AlarmManager.RTC, timeInMillis, pendingIntent);
In this example, we use RTC to trigger an alarm in 5 minutes using a broadcast receiver.
ELAPSED_REALTIME_WAKEUP alarm is used to wake up the device from sleep mode and triggers the alarm. This alarm is ideal for triggering recurring events based on elapsed time.
Example:
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
long timeInMillis = SystemClock.elapsedRealtime() + 300000; //Trigger alarm after 5 minutes
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeInMillis, pendingIntent);
In this example, we use ELAPSED_REALTIME_WAKEUP to trigger an alarm in 5 minutes using a broadcast receiver.
Here are some tips for scheduling alarms using AlarmManager:
AlarmManager is a powerful and versatile tool that can greatly enhance the functionality of your Android application. With the right use and configuration, you can create intelligent and efficient applications that can perform tasks automatically at the perfect time.