如何通过Firebase Messaging API实现推送通知的声音与震动
解决Firebase Messaging API通知无声音震动问题
问题根源
旧版FCM(Legacy HTTP API)和新版HTTP v1 API的配置逻辑差异明显,你当前的代码存在两个关键问题:
- Android通知配置中,
sound设为true不符合新版API要求,必须明确指定为"default"或自定义声音文件名 - 若测试设备为Android 8.0及以上版本,通知渠道的配置优先级高于消息体设置,可能渠道本身未开启声音和震动权限
修正后的代码示例
$fields = [ 'message' => [ 'topic' => $username, 'notification' => $message, 'android' => [ 'priority' => 'HIGH', 'notification' => [ 'sound' => 'default', // 明确指定使用系统默认通知声音 'defaultVibrateTimings' => true, // 若defaultVibrateTimings未生效,可尝试自定义震动节奏 // 'vibrateTimings' => ['0ms', '250ms', '250ms', '250ms'] ], ], ], ];
额外排查步骤
- 检查通知渠道配置:Android 8.0+强制要求使用通知渠道,且渠道需开启声音和震动权限。确保应用Android端创建渠道时配置正确:
// Android端示例代码 NotificationChannel channel = new NotificationChannel("你的渠道ID", "渠道名称", NotificationManager.IMPORTANCE_HIGH); channel.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), null); channel.enableVibration(true); channel.setVibrationPattern(new long[]{0, 250, 250, 250}); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); - 确认消息优先级:必须将
priority设为HIGH,低优先级消息可能被系统限制声音和震动触发 - 自定义声音测试:若使用自定义通知音,需将音频文件放入
res/raw目录,消息中指定文件名(不带后缀),例如'sound' => 'custom_notify_sound'
内容的提问来源于stack exchange,提问作者omega1
相关产品推荐
相关产品推荐

