求助:Flutter Firebase推送通知自定义音效无法生效问题
解决Flutter Firebase推送通知自定义音效问题(Android+iOS后台生效)
Android 端配置(8.0+ 强制要求)
创建带自定义音效的通知渠道
在Android原生代码(如MainActivity或Application类)中创建指定音效的通知渠道,示例代码:import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.core.app.NotificationCompat import io.flutter.embedding.android.FlutterActivity class MainActivity : FlutterActivity() { override fun onCreate(savedInstanceState: android.os.Bundle?) { super.onCreate(savedInstanceState) createCustomSoundChannel() } private fun createCustomSoundChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelId = "custom_sound_channel" val channelName = "自定义音效通知" val channelDesc = "使用自定义音效的通知渠道" val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(channelId, channelName, importance).apply { description = channelDesc // 关联res/raw下的音频文件,文件名不带扩展名 setSound(android.net.Uri.parse("android.resource://${packageName}/raw/test"), NotificationCompat.AUDIO_ATTRIBUTES_DEFAULT) } val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } } }修正FCM请求的渠道ID
你的代码中android_channel_id为空字符串,必须替换为上面创建的渠道ID:'notification': <String, dynamic>{ 'title': title, 'body': body, "sound": "test.wav", 'android_channel_id': "custom_sound_channel" // 填写实际渠道ID },音频文件校验
- 确保
test.wav放在android/app/src/main/res/raw目录,文件名全小写、无特殊字符 - 音频格式要求:PCM 16位,采样率22050Hz/44100Hz,时长不超过30秒
- 确保
iOS 端配置
添加音频文件到项目
- 将
test.wav拖入Xcode项目根目录,勾选"Copy items if needed",并确保目标项目已选中 - 检查
Build Phases > Copy Bundle Resources中包含该文件
- 将
配置Info.plist权限
添加以下键值对,确保后台推送和声音权限生效:<key>UIBackgroundModes</key> <array> <string>remote-notification</string> </array> <key>NSRemoteNotificationUsageDescription</key> <string>需要推送权限接收消息提醒</string>FCM Payload 校验
iOS端sound字段需保留完整文件名(含扩展名),你的代码中"test.wav"符合要求,确保推送为通知消息(包含notification字段),后台状态下iOS会自动播放音效。
通用注意事项
- 必须发送通知消息(含
notification字段),纯数据消息需Flutter本地处理,无法满足后台自动播放音效的需求 - 保持
Priority: high配置,确保消息及时送达后台 - 测试场景:Android关闭APP后台运行、iOS后台/锁屏状态下测试推送音效
内容的提问来源于stack exchange,提问作者muhamad tahsin
相关产品推荐
相关产品推荐

