I’m trying to add an alarm feature to my app that can wake up the device and launch a full screen activity over the lock screen. There doesn’t seem to be any decent tutorials out there that cover the lock screen so I had to experiment on my own.
So from what I’ve read the best way to do this is with a notification and a full screen intent. It works but if I choose to ignore the alarm I find that as soon as I unlock the device later, my app’s default launch activity is displayed. i.e.
- Alarm rings.
- Notification shown and launches full screen activity.
- Hit mute which calls finish() on full screen activity.
- Device back in locked state then screen goes off.
- Unlock later, device showing app’s default launch activity.
I can’t figure out why point 5 happens because it seems to be inconsistent. Sometimes the app activity is left open, sometimes it isn’t.
How do I stop this from happening and why does it happen? Seems finish()
isn’t really ending the activity and is just paused while the device remains locked.
Code tested in SDK 33 emulator.
FullScreenActivity:
fun onClickMute() {
// tried cancelling notification at this point
// but launch activity still open when unlocking device
finish()
}
override fun onAttachedToWindow() {
window?.let {
it.apply {
addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON)
addFlags(WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON)
addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
}
}
}
AlarmBroadcastReceiver:
fun showNotification() {
val launchIntent = Intent(ctx, FullScreenActivity::class.java).also {
it.action = "ringing"
}
// adding these flags don't seem to make a difference
launchIntent.apply {
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
}
val pendingIntent = pendingIntent(ctx,launchIntent)
val mainIntent = Intent(ctx,ActivityAlarmDetails::class.java)
val mainIntentPending = pendingIntent(ctx,mainIntent)
val notif = NotificationCompat.Builder(ctx, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setOnlyAlertOnce(true)
.setContentTitle("Alarm")
.setContentText("ring ring ring")
.setFullScreenIntent(pendingIntent,true)
.setContentIntent(mainIntentPending)
NotificationManagerCompat.from(ctx).notify(REMINDER_ID,notif.build())
}