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

5
我正在使用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:https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#AndroidNotification - JensV
1个回答

10

我也在寻找在Android上为Firebase通知定制声音的解决方案,我通过通知渠道解决了这个问题。

我创建了一个通知渠道,并设置了自定义声音,该声音会在应用程序处于后台状态时接收到通知后播放。

您可以参考以下通知渠道链接。

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

创建通知渠道函数

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 'sound' 负载无法正常工作。尝试使用通知渠道后,它成功了!谢谢! - The Anh Nguyen
3
如果应用程序关闭,这是行不通的,因为代码永远不会运行。参数必须在服务器级别的通知中已经设置好了。 - nibbana
@nibbana 这没有意义,推送通知是针对封闭应用程序的。 - Oliver Dixon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接