簡體   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