Let’s begin by scheduling alarms,
AlarmManager class helps us to execute time-based operations outdoors the scope of the applying. For suppose you may schedule an alarm to remind the person to take his drugs at a specific time within the day.
You may also schedule repeating alarms with the chosen interval of time. This is useful in numerous conditions like reminding the person to take his drugs or to maintain hydrated with an interval of time.
Let’s begin with easy one-time(non-repeating) alarms. To set an alarm first we have to create the
AlarmManager class occasion as proven beneath:
non-public var alarmMgr: AlarmManager? = nullalarmMgr = context.getSystemService(Context.ALARM_SERVICE) as? AlarmManager?
Then we have to create a pending intent that invokes a
BroadcastReceiver the place we are able to carry out the specified actions like show a notification to the person in our case. For now, let’s simply create a easy
BroadcastReceiver with the identify
AlarmReceiver as proven beneath:
class AlarmReceiver : BroadcastReceiver()
override enjoyable onReceive(p0: Context?, p1: Intent?)
TODO("Not but applied")
Now it’s time to create the pending intent to set off the
AlarmReceiver . Take a look:
val alarmIntent = Intent(this, AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
Lastly, it’s time to set an alarm. For this, we’d like three issues, alarm kind, set off time in milliseconds, and the pending intent. The final two are largely self-explanatory, whereas coming to an alarm kind,
AlarmManager provides 4 sorts:
ELAPSED_REALTIME—Set off the pending intent primarily based on the time for the reason that machine was booted, however would not get up the machine. The elapsed time consists of any time throughout which the machine was asleep.
ELAPSED_REALTIME_WAKEUP—Wakes up the machine and triggers the pending intent put up the given time has elapsed since machine boot.
RTC—Set off the pending intent on the given time however doesn’t get up the machine.
RTC_WAKEUP—Wakes up the machine to invoke the pending intent on the given time.
Let’s arrange an alarm to set off in a single minute.
SystemClock.elapsedRealtime() + 60 * 1000,
Scheduling a repeating alarm is sort of much like a one-time alarm. The one distinction is to say the interval between the alarms and use
setRepeating as a substitute of
set . Take a look:
SystemClock.elapsedRealtime() + 60 * 1000,,
1000 * 60 * 15,
The above piece of code triggers the alarm after one minute and repeats the alarm each quarter-hour.