且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android推送通知的自定义声音不起作用(FCM)

更新时间:2023-02-26 21:05:01

这个很好的问题帮助我找到了答案.所以我在这里发布我的答案.创建频道时,请尝试将通知声音设置为通知频道本身.我想根据您的信息,旧的Android版本将根据通知有效负载中的声场播放声音,但是在新版本中,您必须将其直接设置为通知通道本身,因为这是控件的当前位置目前打算由Google提供.我必须卸载并重新安装应用程序才能使此代码更改生效,因为我的频道先前已初始化,并且在第一次初始化后不会更新频道.

This was such a good question that helped me find the answer. So I post my answer here. Try setting the sound of the notifications to notification channels themselves at the time when you create the channels. I suppose, based on your info, the old Android versions will play sound according to the sound field in the notification payload, but in the new versions you would have to set it directly to the notification channels themselves since that is where the control is now currently intended to be by Google. I had to uninstall and reinstall the app for this code change to work, because my channels were previously initialized and the channels won't update after the first initialization.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !notificationChannelsInitialized) {
            val newMessagesChannel = NotificationChannel(NEW_MESSAGES_NOTIFICATION_CHANNEL_ID, "New Messages", NotificationManager.IMPORTANCE_HIGH)

            val notificationSoundUri =
                Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE.toString() + "://" + context.packageName + "/" + R.raw.ns) // ns.wav is my notification sound file in the res/raw folder in Android Studio
            val notificationSoundUriAttributes = AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .build()
            newMessagesChannel.setSound(notificationSoundUri, notificationSoundUriAttributes)

            val notificationManager: NotificationManager =
                context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannels(listOf( newMessagesChannel)) // and other channels
        }