我也在寻找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"
}