gpt4 book ai didi

java - Firebase 推送通知中的自定义声音

转载 作者:行者123 更新时间:2023-12-05 00:13:38 25 4
gpt4 key购买 nike

我正在从 Firebase 向我的 Android 应用程序发送推送通知,但它只在收到通知时播放默认声音。

我在 fcm 通知对象中设置了自定义声音参数 {“sound”:”notificationsound.mp3”} 并且该文件存在于 res/raw 文件夹中,根据 (https://firebase.google.com/docs/cloud-messaging/http-server-ref )但它仍然在所有应用程序状态(背景、前景和已终止)上播放默认声音。这是我在 Android 上发送通知的请求正文:

{
"to" : “some id”,
"notification": {
"title":"asdasd",
"body":"sdsad",
"click_action" : "MAIN",
"sound":"notificationsound.mp3"
},
"data": {
"title" : "Something",
"body" : "Important",
"type" : "message"
},
"priority": "high"
}

如何播放自定义通知声音。

最佳答案

我也在寻找android中firebase通知的自定义声音的解决方案,我已经通过Notification Channel解决了这个问题。

我创建了一个带有自定义声音的通知 channel ,该声音在应用程序后台状态下收到通知后播放。

您可以引用以下通知 channel 的链接。

https://medium.com/exploring-android/exploring-android-o-notification-channels-94cd274f604c

https://developer.android.com/training/notify-user/channels

您需要将您的 mp3 文件放在 /res/raw/ 路径中。

请找到代码。

NotificationManager notificationManager = (NotificationManager) getActivity().getSystemService(NotificationManager.class); // If you are writting code in fragment

NotificationManager notificationManager = (NotificationManager) getSystemService(NotificationManager.class); // If you are writting code in Activity

createNotificationChannel 函数

private void createNotificationChannel() { 
Uri sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + context.getPackageName() + "/" + R.raw.sample); //Here is FILE_NAME is the name of file that you want to play
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library if
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
{
CharSequence name = "mychannel";
String description = "testing";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
NotificationChannel channel = new NotificationChannel("cnid", name, importance);
channel.setDescription(description);
channel.enableLights(true); channel.enableVibration(true);
channel.setSound(sound, audioAttributes);
notificationManager.createNotificationChannel(channel);
}
};

createNotificationChannel();

要实现这一点,您需要在 firebase 通知请求对象中传递 android_channel_id 属性。

{
"notification": {
"body": "this is testing notification",
"title": "My App",
"android_channel_id": "cnid"
},
"to": "token"
}

关于java - Firebase 推送通知中的自定义声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61142155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com