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

问题描述 投票:0回答:1

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

example flow

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

我的初始通知应该发出声音/振动,但如果我正在更新现有(即改变进展状态),那么它不应该发出声音/振动。有没有办法在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())
    }
android notifications
1个回答
1
投票

在所有API级别上,您可以使用setOnlyAlertOnce()禁用通知更新的声音和振动:

如果您只想在通知尚未显示时播放声音,振动和自动收报机,请设置此标志。

builder.setOnlyAlertOnce(true)

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

© www.soinside.com 2019 - 2024. All rights reserved.