NotificationChannel setSound踩坑合集

/ 0评 / 1

调用NotificationChannel.setSound()方法来设置/修改通知声音无效

先看下API注释

/**
 * Sets the sound that should be played for notifications posted to this channel and its
 * audio attributes. Notification channels with an {@link #getImportance() importance} of at
 * least {@link NotificationManager#IMPORTANCE_DEFAULT} should have a sound.
 *
 * Only modifiable before the channel is submitted to
 * {@link NotificationManager#createNotificationChannel(NotificationChannel)}.
 */
public void setSound(Uri sound, AudioAttributes audioAttributes) {
}

setSound生效有两个前提,Channel的importance得大于等于NotificationManager#IMPORTANCE_DEFAULT,其次setSound只有在第一次createNotificationChannel的时候生效

误区二 使用deleteNotificationChannel删除Channel然后再重新创建

先看下API注释

/**
 * Deletes the given notification channel.
 *
 * <p>If you {@link #createNotificationChannel(NotificationChannel) create} a new channel with
 * this same id, the deleted channel will be un-deleted with all of the same settings it
 * had before it was deleted.
 */
public void deleteNotificationChannel(String channelId) {
}

同误区一,既然setSound只有在第一次createNotificationChannel的时候生效,那么我们删除掉Channel再重新创建不就可以了么

通过注释可以看到当我们删除了指定id的channel,当我们重新创建同一个id的channel的时候,新设置的属性都是无效的,会和以前删除的那个channel一模一样

设置通知铃声

private fun initNotifyChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val channelId = ""
        val channelName = ""
        //test.ogg传递test即可
        val sound = getSound(applicationContext.packageName, "raw文件名字", resources)
        val channel = NotificationChannel(
            channelId, channelName, NotificationManager.IMPORTANCE_HIGH
        )
        channel.importance = NotificationManager.IMPORTANCE_HIGH
        channel.setSound(sound, Notification.AUDIO_ATTRIBUTES_DEFAULT)
        channel.enableVibration(true)
        val service =
            (getSystemService(Context.NOTIFICATION_SERVICE) as? NotificationManager)
        service?.let {
            if (it.getNotificationChannel(channelId) == null) {
                service.createNotificationChannel(channel)
            }
        }
    }
}

private fun getSound(pkgName: String, soundName: String, resources: Resources): Uri? {
    return if (TextUtils.isEmpty(soundName)) {
        null
    } else {
        val soundId = resources.getIdentifier(soundName, "raw", pkgName)
        if (soundId != 0) {
            return Uri.parse("android.resource://$pkgName/raw/$soundName")
        }
        return RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
    }
}

铃声文件必须存放在应用的/res/raw路径下,例如“/res/raw/shake.mp3”,对应sound值参数为“/raw/shake”,支持的格式包括MP3、WAV、MPEG等

oppo手机会有兼容性问题,导致声音只会生效一次,原因待定

其他

选中铃声进行播放一下

val mRingtone = RingtoneManager.getRingtone(this, Settings.System.DEFAULT_NOTIFICATION_URI)
mRingtone?.play()

参考文档

https://blog.csdn.net/sam0750/article/details/117533655

https://developer.huawei.com/consumer/cn/doc/development/HMSCore-Guides/android-isound-0000001142717056

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注