Monday, 22 November 2021

How to send a notification without waking the screen on Android

I have a foreground service in my app, whose persistent notification has a timer in it, which means that the notification is sent once per second to update the timer that is shown in the notification. This means that on some devices, where notifications are set to either wake the screen entirely or show a dark version on the screen briefly, the screen is constantly awake.

Is there a way to send the notification in a way that it won't wake up the screen? Setting it as a silent notification on the device fixes this, but the point of a foreground service notification is that it's prominent on the device, so this isn't a great solution, and not all users would know to do that.

This is how I'm building the notification:

NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("Currently Reading")
            .setSound(null)
            .setContentIntent(TaskStackBuilder.create(this).run {
                addNextIntentWithParentStack(timerIntent)
                getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
                )
            })
            .setSmallIcon(R.drawable.ic_launcher_foreground)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)


from How to send a notification without waking the screen on Android

No comments:

Post a Comment