Skip to content

Alarm Manager

Example of how to send a notification at a custom time via Alarm Manager

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

⚠️ Remember to register the receiver in the manifest ℹ️ android.permission.RECEIVE_BOOT_COMPLETED is not necessary if you don’t activate the alarm when the device boots up

Create a BroadcastReceiver for pushing notification

Section titled “Create a BroadcastReceiver for pushing notification”
class AlarmReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
sendNotification(context)
}
private fun sendNotification(context: Context) {
val notificationManager =
context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationId = (100..200).random()
val channelId = "hello_background"
val channel =
NotificationChannel(
channelId,
"hello_background",
NotificationManager.IMPORTANCE_HIGH
)
notificationManager.createNotificationChannel(channel)
val notification = NotificationCompat.Builder(context, channelId)
.setContentTitle("It's time to die")
.setContentText("A test message!!!")
.setSmallIcon(R.drawable.play)
.build()
notificationManager.notify(notificationId, notification)
}
}
@SuppressLint("ScheduleExactAlarm")
fun setExactAlarm(context: Context, triggerTime: Long) {
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(context, AlarmReceiver::class.java)
val pendingIntent = PendingIntent.getBroadcast(
context,
0,
intent,
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerTime, pendingIntent)
}