Firebase Cloud Messaging 在背景收訊息

前陣子將推播服務換成 Firebase,

但發現一個問題:只有在前景時才收得到訊息。

官方文件指出:

App behavior when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.

  • When in the foreground, your app receives a message object with both payloads available.
  • When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.

因此,想在背景收到通知,必須傳送 data message。

使用方式為:

如此一來,即可在背景收到訊息。

有什麼想法嗎?快來跟大家分享你的看法。