繁体   English   中英

Capacitor/Ionic:在后台或应用程序被终止时处理推送通知

[英]Capacitor/Ionic: Handling push notification in background or when app was killed

大家早上好,我已经好几个小时找不到解决方案了。

我使用“PushNotifications”电容器插件( https://capacitor.ionicframework.com/docs/apis/push-notifications/ )收听来自 firebase 的推送通知(通知和数据类型),通知发生得非常好,即使在应用程序被杀死或在后台的情况下,一切都按预期运行。

问题如下:

我想在收到通知时打开应用程序,如果它在后台或者它已被杀死。

  1. 在应用程序处于前台时收到通知的情况下,我可以使用addListener(eventName: "pushNotificationReceived", callback)运行自定义代码,无论如何我都没有问题,因为应用程序是打开的。

  2. 如果在应用程序处于后台时收到通知,我可以强制应用程序保持 backgroundMode 处于活动状态( https://ionicframework.com/docs/native/background-mode )并在收到通知。 (虽然我不太喜欢它,因为它很耗电)

  3. 如果应用程序被杀死,我还没有找到问题的解决方案。

似乎没有办法挂钩自定义代码,以便能够在后台收到推送通知或应用程序被终止时运行,你有没有遇到过这个问题?

谢谢!

我的解决方案是添加: FCM_PLUGIN_ACTIVITY action to AndroidManifest.xml

        <activity
        ...
        android:name="com.appname.MainActivity"
        ...>

        ...
        ...
        ...

        <intent-filter>
            <action android:name="FCM_PLUGIN_ACTIVITY" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

此外,在服务器上,您应该在推送通知 object 中包含该操作:

  const pushNotification = {
  data: {
    ...
  },
  notification: {
    body: body,
    title: title,
    click_action: 'FCM_PLUGIN_ACTIVITY',
  },
};

在您的 ionic 项目中,您可以像下面一样处理pushNotificationActionPerformed并导航到所需的路线:

  PushNotifications.addListener('pushNotificationActionPerformed',
  (notification: PushNotificationActionPerformed) => {
    console.log('Push action performed: ' + JSON.stringify(notification));
  }
);

要在应用程序打开时处理接收推送通知,您应该处理pushNotificationReceived并在需要时自己显示敬酒。

// the app is open, show your own notification if needed
PushNotifications.addListener('pushNotificationReceived',
  (notification: PushNotification) => {
    console.log('push notification received: ' + JSON.stringify(notification));
  }
);

我遇到了同样的问题,并在 AndroidManifest.xml 中使用以下行修复了它

<meta-data android:name="com.google.firebase.messaging.default_notification_channel_id" android:value="@string/default_notification_channel_id" />
<service android:name="com.getcapacitor.CapacitorFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>

对我们来说,如果我们额外安装了 FCM 插件( https://github.com/capacitor-community/fcm ),后台通知(即使在应用程序被杀死之后)也可以工作,我们需要 iOS。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM