Android 13
使用自定义声音创建本地通知
我在res/raw/event_sound.mp3
中有我的event_sound.mp3音频文件
我有以下通知
val notification = NotificationCompat.Builder(context, channelId)
.setContentTitle(title)
.setContentText(description)
.setSmallIcon(R.drawable.bell)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setSound(getUriSoundFile(context))
.build()
我有以下方法来提取我的数据模块中的音频文件。
private fun getUriSoundFile(context: Context): Uri {
val uri = Uri.parse("android.resource://" + "me.androidbox.data" + "/raw/" + "event_sound.mp3")
return uri
}
当我检查完整路径时,我得到以下结果:
android.resource://me.androidbox.data/raw/event_sound.mp3
我已经在我的Application类中设置了我的频道,就像这样:
private fun createNotificationChannel(listOfChannel: Map<String, String>) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
listOfChannel.map { mapOfChannel ->
val notificationManager = getNotificationManager()
val notificationChannel = NotificationChannel(
mapOfChannel.key,
mapOfChannel.value,
NotificationManager.IMPORTANCE_HIGH
)
notificationManager.createNotificationChannel(notificationChannel)
}
}
}
然而,通知只会播放默认的声音,从不播放我的自定义声音。
更新====
我在我的Application类中有以下内容。event_sound直接在以下位置。
raw/event_sound.mp3
android.resource://me.androidbox.presentation/2131558400
这是我的更新代码:private fun createNotificationChannel(listOfChannel: Map<String, String>) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
listOfChannel.map { mapOfChannel ->
val notificationManager = getNotificationManager()
val notificationChannel = NotificationChannel(
mapOfChannel.key,
mapOfChannel.value,
NotificationManager.IMPORTANCE_HIGH
)
val audioAttributes = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT)
.build()
notificationChannel.setSound(getUriSoundFile(), audioAttributes)
notificationManager.createNotificationChannel(notificationChannel)
}
}
}