I have an application that allows the user to interact with notifications. Here is a simple use case: when the user taps on "Action," the app does some processing and updates the notification to show progress and updates it again to show whether the action was successful or not.
Prior to 26, I was able to set the sound/vibration on individual notifications so once the user click on "Action", the transition to the progress state would not make a sound/vibrate (the behavior that I want) but with 26, it seems like those arguments are no longer respected and the sound/vibration settings are only respected on the channel level.
My initial notification is supposed to make a sound/vibrate but if I am updating an existing (i.e. changing to progress state) then it should not make a sound/vibrate. Is there a way to accomplish that on API 26 and above?
Here is the code for setting up the initial state:
private fun sendNotification() {
val builder = NotificationCompat.Builder(this, "channel_id")
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val intent = Intent(this, MyIntentService::class.java)
val pIntent = PendingIntent.getService(this, ID, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val action = NotificationCompat.Action.Builder(
R.drawable.ic_lock_open_white_24dp,
"Action",
pIntent
).build()
builder.setSmallIcon(R.drawable.ic_home_teal_600_24dp)
.setContentTitle("My Title")
.setContentText("My content text")
.setSound(defaultSoundUri)
.addAction(action)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelName = "My Channel"
val description = "Channel Description"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel("channel_id", channelName, importance)
channel.description = description
notificationManager.createNotificationChannel(channel)
}
val manager = NotificationManagerCompat.from(this)
manager.notify(ID, builder.build())
}
And the transition to the progress state (using same id)
private fun updateNotification(notificationId: Int, title: String) {
//This should NOT make sound or vibrate but it does on 26
val builder = NotificationCompat.Builder(this, "channel_id");
builder
.setSmallIcon(R.drawable.ic_home_teal_600_24dp)
.setContentTitle(title)
.setProgress(0, 0, true)
.setContentText("Processing...")
val manager = NotificationManagerCompat.from(this)
manager.notify(notificationId, builder.build())
}
On all API levels, you can disable sound and vibration for notification updates by use setOnlyAlertOnce():
Set this flag if you would only like the sound, vibrate and ticker to be played if the notification is not already showing.
builder.setOnlyAlertOnce(true)
This will ensure that updates to an existing notification won't sound/vibrate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With