【问题标题】:Custom sound in Firebase push notificationFirebase 推送通知中的自定义声音
【发布时间】:2020-07-23 07:29:58
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您的安卓设备可能不允许覆盖通知声音。您使用的是旧版 firebase api,它对于较新的设备也可能无法以相同的方式工作。但这只是一个猜测。也许试试新的 api:firebase.google.com/docs/reference/fcm/rest/v1/…

标签: java android


【解决方案1】:

我也在寻找android中firebase通知自定义声音的解决方案,我已经通过Notification 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"
}

【讨论】:

  • 我正在使用 FCM 发送通知。默认发送 FCM“声音”有效载荷不起作用。尝试使用通知通道后,它起作用了!谢谢!
  • 如果应用程序关闭,这将无法工作,因为代码将永远不会运行。参数必须已在服务器级别的通知中设置
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-16
  • 1970-01-01
相关资源
最近更新 更多