You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic应用前台锁屏时FCM推送无法接收,需点击才触发

解决Ionic FCM前台锁屏时无法接收通知的问题

嘿,我刚好碰到过一模一样的问题,这其实是FCM在应用前台时的默认行为导致的!当应用处于前台时,FCM不会自动把通知推到系统托盘——哪怕屏幕锁着也是如此,因为此时消息会直接发送给你的应用而不是系统通知服务。下面是具体的解决步骤:

核心原因

FCM的notification字段消息在后台/杀死状态下会由系统通知服务处理,自动弹出托盘通知;但在前台时,消息会直接传递给你的应用代码,不会触发系统级的通知展示,锁屏状态下自然就看不到了。

解决方案:手动触发本地通知

我们需要借助Ionic的本地通知插件,在前台收到FCM消息时,手动创建系统级通知,这样即使锁屏也能正常弹出。

1. 安装本地通知插件

首先安装Capacitor的本地通知插件(如果用Cordova的话可以对应使用cordova-plugin-local-notifications):

npm install @capacitor/local-notifications
npx cap sync

2. 修改FCM消息监听逻辑

在你的应用初始化代码(比如app.component.ts)里,监听FCM的前台消息事件,并调用本地通知插件弹出通知:

import { Component } from '@angular/core';
import { FCM } from '@capacitor-fcm/fcm';
import { LocalNotifications } from '@capacitor/local-notifications';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent {
  constructor() {
    this.setupFCMAndLocalNotifications();
  }

  async setupFCMAndLocalNotifications() {
    // 先请求必要的权限:FCM推送权限和本地通知权限
    await Promise.all([
      FCM.requestPermission(),
      LocalNotifications.requestPermissions()
    ]);

    // 监听前台收到的FCM消息
    FCM.onMessage(async (receivedMessage) => {
      // 从FCM消息里提取标题、内容和自定义数据
      const notificationTitle = receivedMessage.notification?.title || '新通知';
      const notificationBody = receivedMessage.notification?.body || '';
      const extraData = receivedMessage.data;

      // 调用本地通知插件,创建系统级通知
      await LocalNotifications.schedule({
        notifications: [
          {
            id: Date.now(), // 用时间戳做唯一ID
            title: notificationTitle,
            body: notificationBody,
            extra: extraData, // 把FCM的data字段传进去,方便后续处理点击事件
            autoCancel: true, // 点击后自动取消通知
            foreground: true, // 允许在前台展示通知
          }
        ]
      });
    });
  }
}

3. 检查锁屏通知权限

别忘确认应用已经获得了锁屏时显示通知的权限:

  • Android:进入应用设置 → 通知 → 确保“在锁屏上显示”已开启
  • iOS:进入设置 → 通知 → 你的应用 → 开启“在锁定屏幕上显示”

额外提示

如果你用的是Cordova版本的FCM插件,逻辑是类似的——监听onNotification事件,判断应用处于前台时,调用本地通知插件触发通知即可。

这样调整后,不管应用是后台、杀死状态还是前台锁屏,都能正常收到系统托盘通知啦!

内容的提问来源于stack exchange,提问作者Hadjer Kh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:58:16