Ionic/Capacitor Android前台FCM推送通知失效求助
Ionic + Capacitor FCM 前台推送通知异常修复方案
问题现象
- 后台/应用杀死状态:通知正常接收、展示,点击可触发
pushNotificationActionPerformed事件实现深度链接。 - 前台状态:
pushNotificationReceived事件正常触发,但无原生通知展示,无法通过点击触发pushNotificationActionPerformed事件,当前临时用Toast替代,体验不佳。
修复方案
1. 调整前端NotificationService代码
移除自定义Toast逻辑,让Capacitor自动处理前台通知的原生展示:
// NotificationService 中监听 pushNotificationReceived 的代码片段 PushNotifications.addListener('pushNotificationReceived', async (notification) => { console.log('🚨 Notification received (Foreground):', notification); // 移除自定义Toast逻辑,交由Capacitor按配置展示原生通知 // 如需额外业务逻辑,可在此添加,但不要拦截原生通知流程 });
2. 确认Capacitor配置正确性
确保capacitor.config.ts的PushNotifications插件配置中,presentationOptions包含alert(前台展示原生通知的核心配置):
// capacitor.config.ts export default defineConfig({ // 其他配置... plugins: { PushNotifications: { presentationOptions: ["badge", "sound", "alert"] } } });
3. 验证Android端通知通道配置
确认MainActivity中创建的通知通道优先级为IMPORTANCE_HIGH,且清单文件已绑定默认通道:
MainActivity通道创建代码(保持现有正确配置)
private void createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationChannel channel = new NotificationChannel( CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH ); channel.setDescription(CHANNEL_DESCRIPTION); channel.enableLights(true); channel.enableVibration(true); channel.setLockscreenVisibility(android.app.Notification.VISIBILITY_PUBLIC); NotificationManager notificationManager = getSystemService(NotificationManager.class); if (notificationManager != null) { notificationManager.createNotificationChannel(channel); Log.d(TAG, "✅ Canal de notificaciones creado: " + CHANNEL_NAME); } } }
Android清单文件默认通道配置(保持现有正确配置)
<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="default" />
4. 后端FCM Payload优化
确保发送的Payload中Android配置关联正确通道,且优先级设为high:
// 后端sendPushNotificationMultiple中的Payload配置 const payload = { notification: { title: titulo, body: mensaje, }, data: { title: titulo, body: mensaje, type: 'chat', conversacionId: conversacionId, receptorId: receptorId, }, android: { priority: 'high', notification: { channelId: 'default', // 与Android端通道ID完全一致 }, }, // APNS配置保持不变 };
关键原理
Capacitor PushNotifications插件默认会根据presentationOptions配置,在前台收到通知时自动展示原生通知。之前的自定义Toast逻辑拦截了原生通知流程,导致无法触发点击事件。移除Toast后,插件会还原原生通知行为,点击通知时将正常触发pushNotificationActionPerformed事件,与后台/杀死状态的交互逻辑保持一致。
内容的提问来源于stack exchange,提问作者Pedro Madrigal
相关产品推荐
相关产品推荐

