gpt4 book ai didi

android - 如何为 channel 上的通知更新禁用声音/振动(API 26+)?

转载 作者:行者123 更新时间:2023-12-04 01:27:12 24 4
gpt4 key购买 nike

我有一个允许用户与通知交互的应用程序。这是一个简单的用例:当用户点击“操作”时,应用程序会进行一些处理并更新通知以显示进度并再次更新以显示操作是否成功。

example flow

在 26 之前,我能够在单个通知上设置声音/振动,因此一旦用户单击“操作”,转换到进度状态不会发出声音/振动(我想要的行为),但是 26,似乎这些参数不再受到尊重,声音/振动设置仅在 channel 级别受到尊重。

我的初始通知应该发出声音/振动,但如果我正在更新现有的(即更改为进度状态),那么它不应该发出声音/振动。有没有办法在 API 26 及更高版本上实现这一点?

下面是设置初始状态的代码:

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())
}

并过渡到进度状态(使用相同的 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())
}

最佳答案

在所有 API 级别上,您可以使用 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)

这将确保对现有通知的更新不会发出声音/振动。

关于android - 如何为 channel 上的通知更新禁用声音/振动(API 26+)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52349288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com