AlarmManager
. The AlarmManager
class lets you launch and repeat a PendingIntent
at a specified time, or after a specified interval.onCheckChanged
listeners for toggle buttons.AlarmManager
.ToggleButton
to set and keep track of the alarm.Toast
messages to notify the user when the alarm is turned on or off.activity_main.xml
layout file. Replace the 'Hello World' TextView
with the following ToggleButton
:Attribute | Value |
android:id | '@+id/alarmToggle' |
android:layout_width | 'wrap_content' |
android:layout_height | 'wrap_content' |
android:textOff | 'Alarm off' |
android:textOn | 'Alarm on' |
app:layout_constraintStart_toStartOf | 'parent' |
app:layout_constraintBottom_toBottomOf | 'parent' |
app:layout_constraintEnd_toEndOf | 'parent' |
app:layout_constraintTop_toTopOf | 'parent' |
onCheckedChangeListener()
method.MainActivity.java
, inside the onCreate()
method, implement the following steps:ToggleButton
by id
.setOnCheckedChangeListener()
on the ToggleButton
instance, and begin entering 'new OnCheckedChangeListener
'. Android Studio autocompletes the method for you, including the required onCheckedChanged()
override method.onCheckedChanged()
is the CompoundButton
that the user tapped, which in this case is the alarm ToggleButton
. The second parameter is a boolean
that represents the state of the ToggleButton
, that is, whether the toggle is on or off.onCheckedChanged()
method, set up an if-else
block using the boolean
parameter. If the alarm was turned on or off, display a Toast
message to the user.deliverNotification()
method that posts the reminder to stand up and walk.MainActivity.java
:mNotificationManager
of the type NotificationManager
.onCreate()
method, initialize mNotificationManager
using getSystemService()
.createNotificationChannel()
.createNotificationChannel()
at the end of onCreate()
.Intent
deliverNotification()
that takes the Context
as an argument and returns nothing.deliverNotification()
method, create an Intent
that you will use for the notification content intent.deliverNotification()
method, after the definition of contentIntent,
create a PendingIntent
from the content intent. Use the getActivity()
method, passing in the notification ID and using the FLAG_UPDATE_CURRENT
flag:PendingIntent
flags tell the system how to handle the situation when multiple instances of the same PendingIntent
are created (meaning that the instances contain the same Intent
). The FLAG_UPDATE_CURRENT
flag tells the system to use the old Intent
but replace the extras
data. Because you don't have any extras in this Intent
, you can use the same PendingIntent
over and over.ic_stand_up
. For example, you could use the directions 'walk' icon: deliverNotification()
method, use the NotificationCompat.Builder
to build a notification using the notification icon and content intent. Set notification priority and other options.deliverNotification()
method, use the NotificationManager
to deliver the notification:onCreate()
, call deliverNotification()
when the alarm toggle button is turned on, passing in the activity context.onCreate()
, call cancelAll()
on the NotificationManager
if the toggle is turned off to remove the notification.AlarmManager
to schedule and deliver the notification every 15 minutes.AlarmManager
. This class will periodically deliver the reminder to stand up. AlarmManager
has many kinds of alarms built into it, both one-time and periodic, exact and inexact. To learn more about the different kinds of alarms, see Schedule repeating alarms.AlarmManager
, like notifications, uses a PendingIntent
that it delivers with the specified options. Because of this, AlarmManager
can deliver the Intent
even when the app is no longer running.setAndAllowWhileIdle()
or setExactAndAllowWhileIdle()
. You can also use the new WorkManager
API, which is built to perform background work either once or periodically. For details, see Schedule tasks with WorkManager
.AlarmManager
can trigger one-time or recurring events that occur even when your app is not running. For real-time clock (RTC
) alarms, schedule events using System.currentTimeMillis()
. For elapsed-time (ELAPSED_REALTIME
) alarms, schedule events using elapsedRealtime()
. Deliver a PendingIntent
when events occur.SystemClock
.AlarmManager
and reacts appropriately:AlarmReceiver
for the Class Name. Make sure that the Exported checkbox is cleared so that other apps can't invoke this broadcast receiver.BroadcastReceiver
with the required method, onReceive()
. Android Studio also adds the receiver to your AndroidManifest
file.AlarmReceiver.java
file:onReceive()
method, including the line that raises the UnsupportedOperationException
.deliverNotification()
method from the MainActivity
class to the AlarmReceiver
class and call it from onReceive()
. You may notice some variables highlighted in red. You define them in the next step.NOTIFICATION_ID
, PRIMARY_CHANNEL_ID
, and mNotificationManager
member variables from the MainActivity
class into the AlarmReceiver
class.mNotificationManager
variable at the beginning of the onReceive()
method. You have to call getSystemService()
from the passed-in context:AlarmManager
is responsible for delivering the PendingIntent
at a specified interval. This PendingIntent
delivers an intent letting the app know it is time to update the remaining time in the notification.MainActivity.java
, inside onCreate()
:Intent
called notifyIntent
. Pass in the context and AlarmReceiver
class.PendingIntent
. Use the context, the NOTIFICATION_ID
variable, the new notify intent, and the FLAG_UPDATE_CURRENT
flag.AlarmManager
to deliver the broadcast every 15 minutes. For this task, the appropriate type of alarm is a`n inexact, repeating alarm that uses elapsed time and wakes the device up if it is asleep. The real-time clock is not relevant here, because you want to deliver the notification every 15 minutes.MainActivity.java
:AlarmManager
in onCreate()
by calling getSystemService()
.onCheckedChanged()
method, remove the call to deliverNotification()
.onCheckedChanged()
method, call setInexactRepeating()
on the alarm manager instance inside the if
case (when the alarm is toggled on).setInexactRepeating()
alarm because it is more resource-efficient to use inexact timing, which lets the system bundle alarms from different apps together. Also, it's acceptable for your app to deviate a little bit from the exact 15-minute interval.setInexactRepeating()
method takes four arguments:ELAPSED_REALTIME_WAKEUP
.SystemClock``.elapsedRealtime()
. Then use a built-in AlarmManager
constant to add 15 minutes to the elapsed time.AlarmManager.INTERVAL_FIFTEEN_MINUTES
constant.PendingIntent
to be delivered.AlarmManager
and notifyPendingIntent
instances from an anonymous inner class, Android Studio may make these instances final
. If it doesn't, you have to make them final
yourself.else
case (when the alarm is toggled off), cancel the alarm by calling cancel()
on the AlarmManager
. Pass in the pending intent used to create the alarm.cancelAll()
on the NotificationManager
, because turning the alarm toggle off should still remove any existing notification.AlarmManager
now delivers your broadcast 15 minutes after the alarm is set, and every 15 minutes after that.SystemClock.elapsedRealtime()
to see the notification immediately. You can also change the interval to a shorter time to make sure that the repeated alarm is working.boolean
variable that is true
if the alarm exists, and false
otherwise. To set this boolean
, you can call PendingIntent.getBroadcast()
with the FLAG_NO_CREATE
flag. If a PendingIntent
exists, that PendingIntent
is returned; otherwise the call returns null
.MainActivity.java
:boolean
that is true
if PendingIntent
is not null
, and false
otherwise. Use this boolean
to set the state of the ToggleButton
when your app starts. This code has to come before the PendingIntent
is created. (Otherwise it always returns true
.)PendingIntent
whose intent matches the intent you are trying to create already exists. The NO_CREATE
flag returns null
unless a PendingIntent
with a matching Intent
exists.alarmUp
:AlarmManager
class also handles the usual kind of alarm clocks, the kind that wake you up in the morning. On devices running API 21 and higher, you can get information about the next alarm clock of this kind by calling getNextAlarmClock()
on the alarm manager.Toast
message. The toast shows the time of the next alarm clock that the user has set.AlarmManager
allows you to schedule tasks based on the real-time clock or on the elapsed time since boot.AlarmManager
provides a variety of alarm types, both periodic and one-time.setAndAllowWhileIdle()
or setExactAndAllowWhileIdle(``)
. You can also use the WorkManager
API, which is built to perform background work either once or periodically. For more information, see Schedule tasks with WorkManager.AlarmManager
. Inexact timing minimizes the load caused by multiple users' devices or multiple apps performing a task at the exact same time.AlarmManager
uses pending intents to perform its operations. You schedule broadcasts, services, and activities using the appropriate PendingIntent
.AlarmManager
? (All set()
methods use inexact timing, unless explicitly stated.)setExact()
method if it is.