Push notification
目前主流為使用免費的 FCM (firebase cloud message) 服務
https://github.com/zo0r/react-native-push-notification
1.先去建立 firebase 專案,之後把 google-service.json 放進 android/app
2.yarn add react-native-push-notification
3.npx react-native link react-native-push-notification
另一模組為:
另一模組為:範例
Local notification
Remote notification
要先設定 App firebase init
1.安裝模組
2.建立專案並放入 google-services.json
android/app/google-services.json
3.
In android/build.gradle
In android/app/build.gradle
4. 重啟後即可
5.新增 config code
之後就會看到 token

監聽 foreground message
加上 onmessage 監聽前台訊息
yarn add @react-native-firebase/messaging
7. server 加上推送
要先初始化 server
完整文件:https://firebase.google.com/docs/cloud-messaging/send-message
然後加上

完整如下:

有關 postman 發送訊息可參考
Background notification
如果關閉 app 後沒有跳通知可以把後端送的 notification payload 移除,或是不使用 setBackgroundMessageHandler 直接只加上 後端送的 notification payload 也會觸發背景與關閉 app 後的通知。
https://rnfirebase.io/messaging/usage#background--quit-state-messages
在最外層 index.js 加上如下即可
不用去 Androidmanifest.xml 新增 permission
如果想要產生在手機桌面跳出 APP 通知的效果,只要把 local notification 放入 裡面即可
記得要先在 component 內建立好 channel
最外層 index.js
成果如下

左上角的灰色方形更改必須加上 ic_notification
1.可使用產生器:
記得圖案必須是白色,然後透明底色
之後把圖片放入以下產生器產生不同尺寸的圖片:
2.然後使用放入對應的 mipmap-*資料夾

3.最後加入以下到 AndroidManifest

點擊通知後跳轉到其他畫面
不建議用 getInitialNotification 可能會再開啟程式時觸發
記得要註冊
方法2:
使用 admin message 傳入 click_action
但因為要給 intent filter ,所以在 react native 只能用上面的方法
https://firebase.google.com/docs/cloud-messaging/send-message#example-notification-click-action
常見問題
1.local notification 沒反應
關掉模擬器,重啟即可
2. server 發出訊息後 device onMessage 沒反應
曾經遇到過了十分鐘後連續跳出,發生在 android 模擬器上
3. 關閉 app後沒收到通知
如果在傳送時加上 notification payload 則可以再關閉 app 後也跳出通知,如果一並帶上 data 屬性則 onmessage也會觸發(如果不加 notification payload 只加上 apns 或 android priority 不會有作用,可以不用加上 android priority)。
Notification payload 可設定參數:https://firebase.google.com/docs/reference/admin/node/admin.messaging.NotificationMessagePayload
如果更改正方形 icon 可設定如下
但記得只有 sendToDevice 等具有 options: MessagingOptions 才可使用https://firebase.google.com/docs/reference/admin/node/admin.messaging.NotificationMessagePayload
如果是 send 或 sendMulticast 必須參考 https://firebase.google.com/docs/reference/admin/node/admin.messaging.Notification

或是直接去 androidmanifest.xml 設定,則可以不用傳送 icon 參數,但這樣 原本的 app icon 會消失

4. admin message 可用方法
https://firebase.google.com/docs/reference/admin/node/admin.messaging.Messaging
Last updated
Was this helpful?