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

Android端Ionic应用后台/关闭时点击通知无法接收数据求助

Android后台/关闭状态下点击通知无法获取数据的解决方案

我之前也碰到过一模一样的问题,和你用的依赖版本几乎一致。这个问题其实是Android系统的推送处理机制导致的:当App处于后台或完全关闭时,Android系统会接管推送通知的展示,点击通知启动App时,pushObject.on('notification')事件并不会触发——只有App在前台运行时,这个事件才会响应推送。而iOS的处理逻辑不同,不管App状态如何,点击通知都会触发该事件,所以iOS端能正常工作。

下面是具体的解决步骤:

1. 添加初始通知数据获取逻辑

你需要在App初始化阶段,手动检查是否是通过点击通知启动的App,并读取对应的数据。cordova-plugin-fcm提供了getInitialNotification方法来实现这个功能,把这段代码加到你的initPushNotification方法里:

initPushNotification() {
  if (!this.platform.is('cordova')) {
    console.warn('Push notifications not initialized. Cordova is not available - Run in physical device');
    return;
  }
  const options: PushOptions = {
    android: { senderID: MY_SENDER_ID },
    ios: { alert: 'true', badge: false, sound: 'true' },
    windows: {}
  };
  const pushObject: PushObject = this.push.init(options);

  // 保留原前台推送处理逻辑
  pushObject.on('notification').subscribe((data: any) => {
    console.log(data);
    this.notificationService.display(data);
  });

  // 新增:处理后台/关闭状态下点击通知启动App的场景
  if ((window as any).FCMPlugin) {
    (window as any).FCMPlugin.getInitialNotification((data: any) => {
      if (data && data.wasTapped) {
        // wasTapped为true说明是通过点击通知启动的App
        console.log('Initial notification data (from background tap):', data);
        this.notificationService.display(data);
      }
    }, (error: any) => {
      console.error('Error fetching initial notification:', error);
    });
  }

  pushObject.on('registration').subscribe((data: any) => {
    // send notification token to server
    // ...
  });

  pushObject.on('error').subscribe(error => console.error('Error with Push plugin' + error));
}

2. 调整推送消息格式(可选但建议)

你的推送消息同时包含notification和data字段,在Android上:

  • 当App前台时,notification和data的数据都会通过pushObject.on('notification')返回;
  • 当App后台/关闭时,系统只会用notification字段展示通知,点击后data字段的数据会被传递到初始通知中,但偶尔会出现字段丢失的情况。

建议你调整推送结构,只保留data字段(把原notification里的内容移到data中),这样无论App处于什么状态,都能拿到完整的推送数据:

{
  "to" : "fDb5ibGYPdE:APA91bFYVW4hb9URujxcAXQIqxEs58vNOoJLXH8bNQW7sKS2ZN",
  "data" : {
    "body" : "great match!!!!",
    "title" : "Portugal vs. Denmark",
    "content_available" : true,
    "priority" : "high",
    "moduleFunctionalId": "filInfo",
    "jsonData": "{id:3884}",
    "additionalData":"bb"
  }
}

这样Android系统会自动用data里的title和body展示通知,同时点击后能获取到所有自定义字段。

3. 验证依赖版本兼容性

你的依赖版本@angular/*": "5.0.0"、@ionic-native/push": "4.5.2"、cordova-plugin-fcm": "2.1.2"是兼容的,但要确保你已经正确安装所有插件,并且在config.xml中配置了Android的senderID:

<plugin name="cordova-plugin-fcm" spec="2.1.2">
    <variable name="SENDER_ID" value="YOUR_SENDER_ID" />
</plugin>

做完这些修改后,重新编译Android项目,测试后台/关闭状态下点击通知的情况,应该就能正常获取到通知数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:48:07