为android设置自定义通知声音似乎不起作用。 我并不是我所做的那样错误。 下面是我的代码:
val defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val urlsound = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://"+R.string.packagename+ "/" + R.raw.sound_notification)
val audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build()
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentText(messageBody)
.setAutoCancel(true)
//.setSound(defaultSoundUri)
.setSound(urlsound)
.setContentIntent(pendingIntent)
其他一切似乎都很好,但自定义的声音就是永远不会出现。 你知道如何改进代码来播放自定义声音吗?
您可能需要创建一个通知通道。 在Android 8之后,所有通知都通过一个通道。 当这个频道被创建,你可以设置一个声音,但你不能改变它之后。 如果你需要你的所有通知有不同的声音,你可以创建一个新的频道,每次删除旧的。
您需要提供audioattributes
来设置声音方法。
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_notification)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(urlsound, audioAttributes)
.setContentIntent(pendingIntent)
记住,不要添加默认notification.default_sound它将覆盖传递的任何声音。
并确保声音文件在raw文件夹中。
在Android8.0
中,您需要为每个通知添加一个通道。 因此您已经在创建通知频道期间设置了声音。
将声音文件放入raw
包中,并传递声音的id和您想要使用它的必要属性。 它将创建带有声音的通知频道
@RequiresApi(Build.VERSION_CODES.O)
private fun Context.createChannel(channelId: String,
importance: Int,
soundResId: Int? = null,
shouldVibrateAndLight: Boolean? = null,
channelName: String? = null,
channelDescriptionRes: Int? = null) {
val notificationManager = NotificationManagerCompat.from(this)
val channel = NotificationChannel(channelId, channelName, importance).apply {
if (channelDescriptionRes != null) description = getString(channelDescriptionRes)
if (soundResId != null) {
val sound = Uri.parse("android.resource://$packageName/$soundResId")
val audioAttributes = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.build()
setSound(sound, audioAttributes)
}
shouldVibrateAndLight?.let {
enableVibration(it)
enableLights(it)
}
}
notificationManager.createNotificationChannel(channel)
}