【问题标题】:How to disable sound/vibration for notification updates on a channel (API 26+)?如何为频道上的通知更新禁用声音/振动(API 26+)?
【发布时间】:2018-09-16 06:39:26
【问题描述】:

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

在 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】:

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

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

    builder.setOnlyAlertOnce(true)
    

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

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-31
      • 1970-01-01
      • 2017-12-18
      • 2019-03-27
      • 1970-01-01
      相关资源
      最近更新 更多