DEV Community

myougaTheAxo
myougaTheAxo

Posted on • Originally published at zenn.dev

AlarmManager + Notification Guide - Precise Scheduling in Android

AlarmManager + Notification Guide

setExactAndAllowWhileIdle

val alarmManager = context.getSystemService<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,
    System.currentTimeMillis() + 60000,
    pendingIntent
)
Enter fullscreen mode Exit fullscreen mode

BroadcastReceiver Notification

class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val notification = NotificationCompat.Builder(context, "CHANNEL_ID")
            .setContentTitle("Alarm!")
            .setSmallIcon(R.drawable.ic_alarm)
            .build()

        NotificationManagerCompat.from(context)
            .notify(1, notification)
    }
}
Enter fullscreen mode Exit fullscreen mode

BOOT_COMPLETED Restore

class BootReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (intent.action == Intent.ACTION_BOOT_COMPLETED) {
            scheduleAllAlarms(context)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Repeating Alarms

alarmManager?.setInexactRepeating(
    AlarmManager.RTC_WAKEUP,
    triggerTime,
    AlarmManager.INTERVAL_DAY,
    pendingIntent
)
Enter fullscreen mode Exit fullscreen mode

Compose UI Integration

@Composable
fun AlarmScheduler(onSchedule: (Long) -> Unit) {
    var selectedTime by remember { mutableStateOf(System.currentTimeMillis()) }

    Button(onClick = { onSchedule(selectedTime) }) {
        Text("Schedule Alarm")
    }
}
Enter fullscreen mode Exit fullscreen mode

8 Android app templates on Gumroad

Top comments (0)