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

标签 java android

我正在从 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/

相关文章:

Java 数据类型声明困惑

java - 在Spring MVC中的Web应用程序的web-inf文件夹中写入txt文件

java - Admob 测试广告加载,实时广告不会

java - 提示用户从数组中选择元素以获取用户信息

java - OSGI kafka 客户端包由于缺少约束导致框架异常

java - 当发生 Java 错误时停止 AppleScript 运行 .jar

javascript - 当用户触摸 Javascript 中的空白屏幕时关闭警告框

android - 如何使用 Cordova/PhoneGap 跟踪地理位置?

android - 绘制包含 InsetDrawable 的层时意外的 LayerDrawable 行为

android - 如何更新 ImageView 中的位图