我正在尝试实现自定义通知声音。有两种不同的声音,一种用于消息,一种用于呼叫,声音在应用程序运行时起作用,我收到通知,但如果应用程序关闭并从最近的应用程序中删除,手机的默认声音也会响起。我使用 Firebase 进行通知。
这种情况主要发生在您在推送通知中获取通知负载时。每当我们在 fcm 有效负载中收到通知和数据时。始终使用 Android 系统的系统托盘访问通知标签。所以它不会考虑您的自定义通知设置。
尝试仅获取 fcm 有效负载中的数据而不是通知。
通知在(Android 和 iOS)和(前台和后台)中的工作方式不同。
- Android 内的通知取决于 通知通道 设置和通道 ID 在有效负载中传递。
- iOS 中的通知自定义取决于 声音文件 传入有效负载。
如果要在Android中为两种不同类型的通知设置声音,首先需要创建两个独立的通道,并在从后端触发通知时将通道ID与特定的声音一起传递。
这是分步说明。
第1步:将声音文件添加到IOS资源和Android原始文件夹中。
第3步:设置前台显示通知通道功能。
AndroidNotificationChannel? channel;
if (message.notification?.body == "You have one Booking Request") {
channel = AndroidNotificationChannel(
'Sound', // id
'High Importance Notifications', // title
description:
'This channel is used for important notifications.', // description
importance: Importance.high,
sound: RawResourceAndroidNotificationSound(
message.notification?.android?.sound),
playSound: true,
);
} else {
channel = const AndroidNotificationChannel(
'normal', // id
'High Importance Notifications', // title
description:
'This channel is used for important notifications.', // description
importance: Importance.high,
playSound: true,
);
}
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
这里Sound和normal是通道ID。为不同的声音创建了“声音”和“正常”通道,
- 在声音通道ID内,自定义声音会响起
- 在正常通道ID内,当有通知时,系统默认响铃。
您可以根据需要设置更多频道。创建频道没有限制。
注意:在 Android 中,一旦根据频道 ID 创建频道,它就会保持相同的配置,直到应用程序被卸载。不同的通道ID可以导致不同的通道配置。但对于一个通道 ID 来说保持不变。当应用程序处于终止状态并且通知从同一通道 ID 到达时,它会自动接管通道 ID 的配置,例如声音、图标和创建的通道的其他自定义设置。并且无需在iOS中创建频道ID
第 4 步:从创建通知的位置更新您的负载。
const message = {
token: token,
notification: {
title,
body,
},
apns: {
headers: {
"apns-priority": "10",
},
payload: {
aps: {
sound:
body != "You have one Booking Request"
? "default"
: "ringtone.wav",
},
},
},
android: {
priority: "high",
notification: {
channelId:
body != "You have one Booking Request" ? "normal" : "Sound",
},
},
data: {
click_action,
},
};
从这段代码中,您可以提取示例
您可以通过替换此body!=“您有一个预订请求”来集成两种不同或两种以上类型的声音通知? “正常”:“声音”,条件符合您的要求。
繁荣,现在无论应用程序关闭还是打开,都会发出不同的通知声音