How to create a fullscreen alarm? [closed]

3 weeks ago 16
ARTICLE AD BOX

I've been trying to create a fullscreen alarm.

I know the main key is AlarmManager for scheduling tasks at a fixed time in the future. I was able to use AlarmManager, an intent and a broadcast receiver to be able to print to logcat a piece of text after several seconds even with app in background.

My desired behavior is inside onReceive for an alarm UI to pop up instead of printing text but not sure what approach to use. I'm a beginner in Android.

Here is my current code: ... means boilerplate

MainActivity.kt

class MainActivity ... { override fun onCreate(savedInstanceState: Bundle?) { ... val scheduler = AlarmScheduler(this) setContent { Theme { var secondsText = 7L var message = "Test message" Button( onClick = { val alarmItem = AlarmItem( time = LocalDateTime.now() .plusSeconds(secondsText), message = message ) scheduler.schedule(alarmItem) }, ) { Text("Schedule") } } } } }

AlarmItem.kt

data class AlarmItem( val time: LocalDateTime, val message: String )

AlarmScheduler.kt

class AlarmScheduler( val context: Context ) { val alarmManager = context.getSystemService(AlarmManager::class.java) fun schedule(item: AlarmItem) { val intent = Intent(context, AlarmReceiver::class.java) intent.putExtra("EXTRA_MESSAGE", item.message) alarmManager.setExactAndAllowWhileIdle( AlarmManager.RTC_WAKEUP, item.time.atZone(ZoneId.systemDefault()).toEpochSecond() * 1000, PendingIntent.getBroadcast( context, item.hashCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) ) } }

AlarmReceiver.kt

class AlarmReceiver: BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) { val message = intent.getStringExtra("EXTRA_MESSAGE") println("Alarm triggered: $message") }

}

Read Entire Article