Disable sound from NotificationChannel

前端 未结 15 1375
时光说笑
时光说笑 2020-11-27 15:50

Today I started targeting API 26 which forced me to use Notification Channels.

My problem is that now on each new notification (including updates to it) an annoying

15条回答
  •  天命终不由人
    2020-11-27 16:40

    I have tested a lot of android devices,the following code works for me properly

    Firstly, create a notificationBuilder, if your Build.Version is bigger than 26, please add a new channel.

      private val notificationBuilder: NotificationCompat.Builder by lazy {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) NotificationCompat.Builder(context) else {
                val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
                val channelId = "MUSIC"
                val channelName = "音乐控制栏"
                val importance = NotificationManager.IMPORTANCE_MIN
                val channel = NotificationChannel(channelId, channelName, importance)
    
                manager.createNotificationChannel(channel)
                channel.enableLights(false)
                channel.vibrationPattern = longArrayOf(0L)
                channel.enableVibration(false)
                channel.setSound(null, null)
                NotificationCompat.Builder(context, channelId)
            }
    
        }
    

    Secondly, init this notificationBuilder, and set sound null

       notificationBuilder.setDefaults(Notification.DEFAULT_LIGHTS ).setVibrate( longArrayOf(0L)).setSound(null)
    

    Thirdly,if build.version is bigger than 24, please set its priority.

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                notificationBuilder.priority = NotificationManager.IMPORTANCE_MIN
            }
    

    Hope that works for you.

提交回复
热议问题