如何为Android推送通知设置自定义声音(Flutter+Firebase场景)
Flutter Android Firebase推送自定义通知声音配置方案
一、前台通知配置(直接通过AndroidNotificationDetails设置)
当App处于前台时,可直接在AndroidNotificationDetails中指定自定义声音,代码示例如下:
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; // 初始化本地通知插件 final FlutterLocalNotificationsPlugin _notificationsPlugin = FlutterLocalNotificationsPlugin(); // 构建Android通知详情 final androidDetails = AndroidNotificationDetails( 'custom_notification_channel', // 自定义通道ID '自定义通知通道', // 通道名称 channelDescription: '带自定义声音的通知通道', importance: Importance.max, priority: Priority.high, // 配置自定义声音:传入res/raw下的文件名(不带.m4a后缀) sound: const AndroidNotificationSound('my_custom_sound'), ); final notificationDetails = NotificationDetails(android: androidDetails); // 触发通知 await _notificationsPlugin.show( 0, '测试标题', '带自定义声音的通知内容', notificationDetails, );
二、后台/杀死状态通知配置(依赖通知通道)
App在后台或被杀死时,FCM推送由Android系统接管,必须确保通知通道已预先配置好自定义声音:
1. 初始化带声音的通知通道
在App启动时创建通道(只需执行一次):
Future<void> _setupNotificationChannel() async { const channel = AndroidNotificationChannel( 'custom_notification_channel', // 与前台配置的通道ID保持一致 '自定义通知通道', description: '带自定义声音的通知通道', importance: Importance.max, // 绑定自定义声音 sound: const AndroidNotificationSound('my_custom_sound'), ); await _notificationsPlugin .resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>() ?.createNotificationChannel(channel); }
2. FCM推送Payload指定通道
通过Firebase控制台或API发送推送时,必须在payload中指定通道ID,确保系统使用你配置的通道:
{ "notification": { "title": "后台测试通知", "body": "后台推送的自定义声音通知" }, "android": { "notification": { "channel_id": "custom_notification_channel" // 与创建的通道ID完全匹配 } }, "token": "目标设备的FCM Token" }
三、核心注意事项
- 声音文件需放在
android/app/src/main/res/raw目录下,文件名只能用小写字母、数字和下划线,不能有空格或特殊字符(例如my_custom_sound.m4a) AndroidNotificationSound的参数只需要文件名,不需要带后缀- 通知通道一旦创建,后续修改声音需要用户手动在系统设置中更新,或卸载重装App,所以首次配置要确保正确
- 测试后台推送时,需完全退出App(不要留在后台),验证声音是否生效
内容的提问来源于stack exchange,提问作者mathems32
相关产品推荐
相关产品推荐

