如何确保我的通知声音在所有设备上都能可靠播放?

时间:2020-06-11 08:49:42

标签: android audio notifications firebase-cloud-messaging

我的应用程序设置了两个通知通道,每个通道都有自己的声音效果。但是用户说声音在某些设备(例如Pixel)上无法正常工作。这是我的设置。我可以做些什么来改善频道设置,以确保声音(保存在res / raw /中的两个.mp3文件)尽可能可靠地播放(作为背景通知,而不是前景)?我缺少更好的音频设置,格式或配置吗?

我正在使用Firebase Cloud Messaging。这是创建频道的代码:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val importance = NotificationManager.IMPORTANCE_HIGH

            val audioAttributes = AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_ALARM)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setFlags(FLAG_AUDIBILITY_ENFORCED)
                .build()

            val newChannel = NotificationChannel(channelId, name, importance)
            newChannel.description = description
            newChannel.importance = IMPORTANCE_HIGH

            newChannel.setSound(sound, audioAttributes)
            return newChannel
}

下面是获取声音URI的代码:

private fun createSoundUri(soundNum: Int, context: Context):Uri? {
val scheme = ContentResolver.SCHEME_ANDROID_RESOURCE
val packageName = context.packageName
val root = "$scheme://$packageName/"

return when(soundNum) {
    0 -> Uri.parse(root + R.raw.sound1)
    1 -> Uri.parse(root + R.raw.sound2)
    2 -> Settings.System.DEFAULT_NOTIFICATION_URI
    else -> null
    }
}

1 个答案:

答案 0 :(得分:0)

我使用FCM接收数据,然后启动了一个活动,启动了我应用中的媒体播放器。

MediaPlayer mediaPlayer = MediaPlayer.create(this,R.raw.ringtone); mediaPlayer.setLooping(true); mediaPlayer.start();

也许您可以使用这个想法