CapacitorJS+FCM应用后台/杀死状态无法接收推送通知问题
FCM后台/杀死状态接收失败排查方案
针对你用CapacitorJS v6 + Svelte + PHP后端开发时,前台能收FCM但后台/杀死状态收不到的问题,从以下几个核心环节逐一排查:
1. Android清单文件配置校验
确认自定义
FirebaseMessagingService注册正确,intent-filter的action不能错:<service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>android:exported设为false避免外部触发,确保action严格匹配com.google.firebase.MESSAGING_EVENT。Android 13+必须声明通知权限,否则后台无法展示通知:
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />若需处理令牌刷新,确认
FirebaseInstanceIdService注册(Capacitor v6可能已封装,但自定义服务需检查):<service android:name=".MyFirebaseInstanceIdService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.INSTANCE_ID_EVENT" /> </intent-filter> </service>
2. 自定义FirebaseMessagingService实现检查
- 明确FCM消息规则:带
notification字段的通知消息,后台/杀死状态下由系统直接展示,不会进入onMessageReceived;仅带data字段的数据消息才会触发该方法。如果你的推送是通知消息,重点检查系统通知通道配置。 - 必须重写
onNewToken方法,确保令牌刷新后能同步到PHP后端:@Override public void onNewToken(String token) { super.onNewToken(token); // 实现令牌上报逻辑,更新后端存储的设备令牌 sendTokenToServer(token); } onMessageReceived内不要做耗时操作,避免被系统回收,复杂任务用WorkManager处理。
3. CapacitorJS端推送初始化验证
- 确认
@capacitor/push-notifications插件安装并正确初始化:import { PushNotifications } from '@capacitor/push-notifications'; async function initPushNotifications() { await PushNotifications.requestPermissions(); await PushNotifications.register(); PushNotifications.addListener('registration', (res) => { // 将设备令牌发送到PHP后端保存 console.log('Push Token:', res.value); }); PushNotifications.addListener('pushNotificationReceived', (notification) => { console.log('前台收到推送:', notification); }); PushNotifications.addListener('pushNotificationActionPerformed', (action) => { console.log('推送点击事件:', action); }); } - 检查
capacitor.config.ts的Android推送配置,确保图标和颜色对应资源文件:export default defineConfig({ android: { push: { icon: "@mipmap/ic_notification", color: "#FFFFFF" } } });
4. PHP后端推送请求修正
- 必须设置
priority: high,Android后台推送依赖高优先级唤醒应用: - 通知消息格式示例(后台由系统展示):
$fcmData = [ 'to' => $deviceToken, 'notification' => [ 'title' => '新通知', 'body' => '这是一条测试通知', 'icon' => 'ic_notification' // 对应Android资源图标 ], 'data' => [ 'page' => 'home' // 自定义跳转参数 ], 'priority' => 'high' ]; - 数据消息格式示例(需自行处理展示):
$fcmData = [ 'to' => $deviceToken, 'data' => [ 'title' => '数据消息', 'body' => '后台触发的自定义消息', 'customData' => 'xxx' ], 'priority' => 'high' ]; - 确认请求头包含有效的FCM服务器密钥:
$headers = [ 'Authorization: key=' . YOUR_FCM_SERVER_KEY, 'Content-Type: application/json' ];
5. 额外排查点
- 检查设备通知权限:确保应用的后台通知、自启动权限已开启(小米、华为等厂商需手动在系统设置中允许)。
- 查看Logcat日志:过滤
FirebaseMessaging、Notification关键词,查找推送接收失败的错误信息。 - 测试Doze模式关闭:开发者选项中关闭“电池优化”,避免系统限制后台推送。
- 验证FCM密钥:确认服务器密钥未过期、权限足够(可在Firebase控制台重新生成)。
内容的提问来源于stack exchange,提问作者Loderunner
相关产品推荐
相关产品推荐

